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
题意:
每个节点都加上比它大的,5+13 = 18, 2 + 5 + 13 = 20,13是最大的所以不用加
思路:
后续遍历,先遍历右子树,再遍历左子树 ,然后逐个往前加
后续遍历的结果是:[13,5,2]
13是最大的,不用加(相当于加0) 得到 [13, 5, 2]
5 加上前面的13, 得到 [13, 18, 2]
2 加上前面的18,得到[13, 18, 20]
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) {
if(root == null) {
return root;
}
convertBST(root.right);
root.val += sum;
sum = root.val;
convertBST(root.left);
return root;
}
}