Convert BST to Greater Tree
Description
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 1
Solution
题目的意思其实很清楚,它说的是让当前的节点加上之前遍历过的【节点和】得到的一个新值,没有那么复杂。
明确递归的顺序,访问从右节点开始,然后根节点,最后左节点,而在访问时,需要维护一个不断更新的sum值即可。不必考虑先序,中序,后序遍历。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int sum=0;
public TreeNode convertBST(TreeNode root) {
sum=0;
addSum(root);//root前面不用加TreeNode
return root;
}
public void addSum(TreeNode root){
if(root!=null){
addSum(root.right);
sum+=root.val;
root.val=sum;
addSum(root.left);
}
}
}