538-Convert BST to Greater Tree

kevin聰發表於2018-04-26

Description

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

問題描述

給定二叉排序樹, 轉換該二叉排序樹, 使得其每個節點的值為大於它的值的節點值之和


問題分析

“傳統的”中序遍歷, 獲取的二叉排序樹的遞增值序列, 那麼我們不妨轉換下思想, 將遍歷左右子樹的順序顛倒, 使得遍歷的值為由大到小排列, 通過sum累計值, 將其賦值給遍歷的當前節點即可

注意一下, 對於二叉排序樹來說, 中序遍歷通常比較重要(遞增值序列), 一般遇到問題可以優先考慮


解法1

/*
這種解法不太優雅
首先通過"傳統的"中序遍歷獲取遞增值序列, 將該序列儲存在一個List中, 然後逆序累加
*/
class Solution {
    private int index;
    private List<Integer> res;

    public TreeNode convertBST(TreeNode root) {
        index = 0;
        res = new ArrayList<Integer>();
        TreeNode node = root;
        inorder(node);

        int sum = 0;
        for(int i = res.size() - 1;i >= 0;i--){
            sum += res.get(i);
            res.set(i,sum);
        }

        node = root;
        convert(node);

        return root;
    }

    public void convert(TreeNode root){
        if(root == null) return;

        convert(root.left);
        root.val = res.get(index++);
        convert(root.right);
    }

    public void inorder(TreeNode root){
        if(root == null) return;

        inorder(root.left);
        res.add(root.val);
        inorder(root.right);
    }
}

解法2

//這種解法就是問題分析中的解法
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);
    }

}

相關文章