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.
Recursion
Time Complexity
O(N)
Space Complexity
O(1)
思路
一看到BST,直接可以想到中序遍历了,这题和普通中序遍历不同的地方在于,因为它要把整颗树中比自己大的点加起来,对于BST中的点,比自己大的点只有可能是自己右边的点,分治法先找到右边最大的,keep一个global的sum,从右开始做的特殊的中序遍历到的每一个点的值都是自己本身加上之前遍历过的所有点的和。
代码
private int sum = 0;
public TreeNode convertBST(TreeNode root) {
// Write your code here
if(root == null) return null;
helper(root);
return root;
}
private void helper(TreeNode root){
if(root == null) return;
helper(root.right);
root.val += sum;
sum = root.val;
helper(root.left);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。