给予一颗二叉搜索树,每个节点都加上大于他的所有节点的和, 如节点 3, 有两个节点大于他, 分别是 10, 15, 那么节点 3 的值就要变为: 3 + 10 + 15 = 28.
例 :
给予树:
5
/ \
2 13
返回树:
18
/ \
20 13
这道题很巧妙, 因为是一颗二叉搜索树, 所以只有所有右子树才会比当前节点大, 那么当前节点加上所有右子树的和即可, 根据这个思路, 我们可以采用后序遍历, 根据 右 -> 中 -> 左
的顺序, 所以我们总是能先得到 所有右字树的和, 然后到 中, 使用 中 = 中 + 右 即可. 这时的 中 就又称为最大的节点了.
/**
* 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) {
if (root == null) {
return null;
}
convertBST(root.right);
root.val += sum;
sum = root.val;
convertBST(root.left);
return root;
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Convert BST to Greater Tree. Memory Usage: 37.4 MB, less than 99.66% of Java online submissions for Convert BST to Greater Tree.