每日一道LeetCode——把二叉搜索树转换为累加树

题目:

在这里插入图片描述
我的解法:两遍递归
在不了解二叉树的基础上,我用笨方法做了一遍,先遍历一遍整个二叉搜索树,将所有的值存到List里,再次遍历整个二叉树,修改每个位置对应的值。(这样做虽然可以正确求解,但是时间复杂度太高)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<Integer> nums = new ArrayList<Integer>();

    public TreeNode convertBST(TreeNode root) {
        if (root==null){
            return null;
        }
        addNum(root);
        TreeNode tn = changeVal(root, nums);
        return tn;
    }

    // 遍历每个结点左右子结点的值
    public void addNum(TreeNode tn){
        nums.add(tn.val);
        if(tn.left!=null){
            addNum(tn.left);
        }
        if(tn.right!=null){
            addNum(tn.right);
        }
    }

    // 修改每个结点的值
    public TreeNode changeVal(TreeNode tn, List<Integer> nums){
        int sum = 0;
        for(int i=0; i<nums.size(); i++){
            if(nums.get(i)>tn.val){
                sum = sum + nums.get(i);
            }
        }
        tn.val = tn.val + sum;
        if(tn.left!=null){
            changeVal(tn.left, nums);
        }
        if(tn.right!=null){
            changeVal(tn.right, nums);
        }
        return tn;
    }

}

在这里插入图片描述
在这里插入图片描述
官方解法一:反序中序遍历

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

官方解法二:Morris 遍历
在这里插入图片描述

class Solution {
    public TreeNode convertBST(TreeNode root) {
        int sum = 0;
        TreeNode node = root;

        while (node != null) {
            if (node.right == null) {
                sum += node.val;
                node.val = sum;
                node = node.left;
            } else {
                TreeNode succ = getSuccessor(node);
                if (succ.left == null) {
                    succ.left = node;
                    node = node.right;
                } else {
                    succ.left = null;
                    sum += node.val;
                    node.val = sum;
                    node = node.left;
                }
            }
        }

        return root;
    }

    public TreeNode getSuccessor(TreeNode node) {
        TreeNode succ = node.right;
        while (succ.left != null && succ.left != node) {
            succ = succ.left;
        }
        return succ;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值