Given the root of 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.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.
Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
Example 1:
把BST每个节点的值都换成 节点值+比它大的所有节点值的和
思路:
观察了一下,发现是按照右子树,root,左子树的顺序求和加到root.val上的,可以写一个按这种顺序遍历求和
class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
rightTraversal(root);
return root;
}
void rightTraversal(TreeNode root) {
if(root == null) return;
rightTraversal(root.right);
sum += root.val;
root.val = sum;
rightTraversal(root.left);
}
}