天天看點

Leetcode 538. Convert BST to Greater Tree

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.

題目大意是: 把一個樹變成另外一個樹,那個樹每一個節點是原來的樹所有比它大的節點之和。

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      

1、右節點不變(因為BST的性質),目前節點加(2+13),左節點加(5+13).

2、用歸遞,inorder traverse tree,但是先右再左

public class Solution {
    int sum = 0;
    
    public TreeNode convertBST(TreeNode root) {
        convert(root);
        return root;
    }
    
    public void convert(TreeNode cur) {
        if (cur == null) return;
        convert(cur.right);
        cur.val += sum;
        sum = cur.val;
        convert(cur.left);
    }
}