Idiot-maker

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

https://leetcode.com/problems/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:

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

解题思路:

右子树->root->左子树的顺序,从下往上开始处理。

对于每个节点,记录往前的累加和sum,在置到root上。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode convertBST(TreeNode root) {
        int[] sum = new int[1];
        helper(root, sum);
        return root;
    }
    
    public void helper(TreeNode root, int[] sum) {
        if (root ==null) {
            return;
        }
        helper(root.right, sum);        
        root.val += sum[0];
        sum[0] = root.val;
        helper(root.left, sum);
    }
}

 

posted on 2018-11-21 07:35  NickyYe  阅读(93)  评论(0编辑  收藏  举报