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算法分析:
用"中序遍历"的方式访问每个节点的值,并将该节点的值累加到一个 int sum 变量上,并用该 sum 变量更新该节点的值。要注意的是,此处的中序遍历是先遍历右子树,再访问根节点,然后再遍历左子树(因为 BST 根节点的值小于右子树所有节点的值,大于左子树所有节点的值)。
Java 算法实现:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int sum=0;
public TreeNode convertBST(TreeNode root) {
sum=0;
addSum(root);
return root;
}
public void addSum(TreeNode root){
if(root!=null){
addSum(root.right);
sum+=root.val;
root.val=sum;
addSum(root.left);
}
}
}