LeetCode Top 100 Liked Questions 538. Convert BST to Greater Tree (Java版; Easy)

welcome to my blog

LeetCode Top 100 Liked Questions 538. Convert BST to Greater Tree (Java版; Easy)

题目描述
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
class Solution {
    public TreeNode convertBST(TreeNode root) {
        if(root==null){
            return root;
        }
        //反中序遍历, 迭代版
        Stack<TreeNode> s = new Stack<>();
        int sum = 0;
        TreeNode cur = root;
        while(!s.isEmpty() || cur!=null){
            while(cur!=null){
                s.push(cur);
                cur = cur.right;
            }
            cur = s.pop();
            sum+=cur.val;
            cur.val = sum;
            cur = cur.left;
        }       
        return root;
    }
}
class Solution {
    //反中序遍历的累加和
    private int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        if(root==null){
            return root;
        }
        convertBST(root.right);
        sum += root.val;
        root.val = sum;
        convertBST(root.left);
        return root;
    }
}
class Solution {
    public TreeNode convertBST(TreeNode root) {
        core(root, 0);
        return root;
    }
    //因为是搜索二叉树, 所以可以以右根左的顺序遍历, 这样是降序
    private int core(TreeNode root, int parentSum){
        if(root==null){
            return 0;
        }
        //right
        int R = core(root.right, parentSum);
        //root
        int tmp = root.val;
        root.val = root.val + R + parentSum;
        //left
        int L = core(root.left, root.val);
        return L + tmp + R;
    }
}
最开始的错误原因, 估计之后看就看不懂了, 主要是提醒自己得熟练的画图梳理递归逻辑

错误原因:root右子树的考虑了root父节点的信息, 重复了, root右子树应该返回1

第一次做; 考察二叉树遍历; 采用右根左的形式; 涉及到前缀和, 需要很小心; 返回值和直接功能分离
/*
DFS; 右根左的形式遍历二叉树, 记录累计和, 将累计和加入当前节点上
*/
class Solution {
    public TreeNode convertBST(TreeNode root) {
        if(root==null)
            return null;
        core(root, 0);
        return root;
    }
    public int core(TreeNode root, int preSum){
        if(root==null)
            return 0;
        //右; 新条件新递归
        int rightRes = core(root.right, preSum);
        
        //根; 当前条件
        //记录当前节点的原始值
        int old = root.val;
        //更新当前节点的值
        root.val = root.val + rightRes + preSum;
        
        //左; 新条件新递归
        int leftRes = core(root.left, root.val);
        
        //核心: 返回的是以root为根的子树的原始值的和
        return leftRes + old + rightRes;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值