Problem:
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Explanation:
在搜索二叉树中,让每个结点的值变为比他大的所有结点的值之和。
My Thinking:
My Solution:
Optimum Thinking:
- 递归,使用后序遍历,从大到小遍历,维护一个累加数。
- 使用栈迭代,先遍历右结点。
Optimum Solution:
(1)
class Solution {
private int sum=0;
public TreeNode convertBST(TreeNode root) {
if (root != null) {
convertBST(root.right);
sum += root.val;
root.val = sum;
convertBST(root.left);
}
return root;
}
}
(2)
class Solution {
public TreeNode convertBST(TreeNode root) {
int sum=0;
Stack<TreeNode> stack=new Stack<>();
TreeNode node=root;
while(!stack.isEmpty()||node!=null){
while(node!=null){
stack.add(node);
node=node.right;
}
node=stack.pop();
sum+=node.val;
node.val=sum;
node=node.left;
}
return root;
}
}