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
解釋下題目:
給定一顆二分搜索樹,對每個節(jié)點進(jìn)行如此操作:將所有比它大的數(shù)字加起來,加到它上面
1. 遞歸
實際耗時:xxms
int globalSum = 0;
public TreeNode convertBST(TreeNode root) {
convert(root);
return root;
}
public void convert(TreeNode cur) {
if (cur == null) {
return;
}
convert(cur.right);
cur.val += globalSum;
globalSum = cur.val;
convert(cur.left);
}
??思路:首先確定這是一個二分搜索樹的圆,所以大小其實很容易判斷徘跪,只需要一直往右走西雀,就能找到最大的那個桐早,而最大的那個是不需要加任何數(shù)字的躯泰;然后找到次小的拂苹,這個次小的就需要加上最大的那個數(shù)字了安聘。以此進(jìn)行遞歸即可得到最后的解。