GuilinDev

Lc0538

05 August 2008

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.

Example:

1
2
3
4
5
6
7
8
9
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

Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/

分析

先递归到右子树,这样加的值会少一些;然后做相加操作,然后递归到左子树。或者维护一个变量,记录右子树中应该加的sum,然后从右边开始遍历。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        inorder(root);
        return root;
    }
    private void inorder(TreeNode node) {
        if (node == null) {
            return;
        }
        inorder(node.right); // 直到最右子树
        node.val += sum;
        sum = node.val; //已经加过了
        inorder(node.left); // 最后遍历左子树
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    public TreeNode convertBST(TreeNode root) {
        dfs(root, 0);
        return root;
    }
    public int dfs(TreeNode root, int val) {
        if(root == null) {
            return val;
        }
        int right = dfs(root.right, val);
        int left = dfs(root.left, root.val + right);
        
        root.val = root.val + right;
        
        return left;
    }
}