538. Convert BST to Greater Tree
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.
Example:
Input:
The root of a Binary Search Tree like this:
5
/ \
2 13
Output:
The root of a Greater Tree like this:
18
/ \
20 13
Analysis:
2 pass.
First pass just simple recursive tree scan to get the sum s of all nodes.
Second pass, in-order recursive traverse to do following at visit:
s = s - root.val;
root.val += s;
Complexity:
Time: O(N)
Space: O(logn)
Code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int s = 0;
public TreeNode convertBST(TreeNode root) {
if(root == null)
{
return null;
}
s = sum(root);
traverse(root);
return root;
}
private int sum(TreeNode root)
{
if(root == null)
{
return 0;
}
return root.val + sum(root.left) + sum(root.right);
}
private void traverse(TreeNode root)
{
if(root == null){
return;
}
traverse(root.left);
s = s - root.val;
root.val += s;
traverse(root.right);
}
}