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.

答案
用global variable accumulate current sum, traverse in reversed order

class Solution {
    int sum = 0;
    
    public TreeNode convertBST(TreeNode root) {
        recur(root);
        return root;
    }
    
    // Just traverse the tree in reverse order, and add
    public void recur(TreeNode root) {
        if(root == null) return;
        
        // go right
        recur(root.right);
        root.val = root.val + sum;
        sum = root.val;
        // go left
        recur(root.left);
    }
}

without global variable:

class Solution {
    public TreeNode convertBST(TreeNode root) {
        recur(root, 0);
        return root;
    }
    
    // Just traverse the tree in reverse order, and accumulate the sum using return value
    public int recur(TreeNode root, int sum) {
        if(root == null) return sum;
        
        // go right
        int right = recur(root.right, sum);
        root.val = root.val + right;
        
        // go left
        int left = recur(root.left, root.val);
        return left;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容