Given the root of 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 the sum of all keys greater than the original key in BST.
Naive approach will be for every node, traverse the tree and find out all the nodes which are greater and update the node. But the time complexity of this approach will be O(n^2).
Since this is a BST, the right most node in the BST is the biggest node among all the nodes. So, we can start from right, i.e. we do a reverse inorder traversal to traverse the nodes of the tree in descending order. Since we are visiting the nodes in the decreasing order, all we care about is maintaining the running sum of the nodes visited thus far.
In the process, we keep track of the running sum of all nodes which we have traversed thus far.
publicclassSolution {
privateint sum = 0;
public TreeNode bstToGst(TreeNode root) {
if (root ==null) {
returnnull;
}
bstToGst(root.right); //visit the right node first sum += root.val; //update the sum for the next node root.val= sum;
bstToGst(root.left);
return root;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
public TreeNode bstToGst(TreeNode root) {
reverseInorder(root, new TreeNode(0));
return root;
}
privatevoidreverseInorder(TreeNode root, TreeNode sum) {
if (root ==null) {
return;
}
int right = reverseInorder(root.right, sum);
sum.val+= root.val;
root.val= sum.val;
return reverseInorder(root.left, sum);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
public TreeNode bstToGst(TreeNode root) {
reverseInorder(root, 0);
return root;
}
privateintreverseInorder(TreeNode root, int sum) {
if (root ==null) {
return sum;
}
int right = reverseInorder(root.right, sum); // pass in provided sum for accumulation root.val= root.val+ right;
return reverseInorder(root.left, root.val); // pass in updated sum }
}
classSolution {
public TreeNode bstToGst(TreeNode root) {
Deque<TreeNode> stk =new ArrayDeque<>();
TreeNode curr = root;
int sum = 0;
while (curr !=null||!stk.isEmpty()) {
while (curr !=null) { // save right-most path of the current subtree stk.push(curr);
curr = curr.right;
}
curr = stk.pop(); // pop out by reversed in-order. sum += curr.val; // update sum. curr.val= sum; // update node value. curr = curr.left; // move to left branch. }
return root;
}
}