每日随机一题 leetcode538. 把二叉搜索树转换为累加树

题:
在这里插入图片描述


方法1:哈希表

class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode convertBST(TreeNode root) {
        if (root == null) return null;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        dfsCreateMap(root, map);
        dfsCreateSumTree(root, map);
        return root;
    }

    public static void dfsCreateMap(TreeNode root, Map<Integer, Integer> map) {
        map.put(root.val, 0);
        // 遍历map里已经有的数value,如果当前数val >= value ,则map对应的value+=val
        // 因为是二叉搜索树,所以采用左中右的顺序进行遍历
        //递归的看左子树
        if (root.left != null)
            dfsCreateMap(root.left, map);

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            Integer value = entry.getKey();
            if (root.val >= value) {
                map.replace(entry.getKey(), entry.getValue() + root.val);
            }
        }

        //递归的看右子树
        if (root.right != null)
            dfsCreateMap(root.right, map);
    }

    public static void dfsCreateSumTree(TreeNode root, Map<Integer, Integer> map) {
        root.val = map.get(root.val);
        //递归的看左子树
        if (root.left != null)
            dfsCreateSumTree(root.left, map);
        //递归的看右子树
        if (root.right != null)
            dfsCreateSumTree(root.right, null);
    }

方法2:直接搞,优化一下,根本不需要哈希表

public TreeNode convertBST(TreeNode root) {
        if (root == null) return null;
        // 法二,直接左中右的顺序遍历,搞一个当前累加和
        // 先找到最右面,就是最小的值
        int[] curSum = {0};
        __dfs(root,curSum);
        return root;
    }

    public static void __dfs(TreeNode root,int[] curSum){
        // 递归的看右子树
        if(root.right!=null)
            __dfs(root.right,curSum);

        // 处理当前值
         
        root.val += curSum[0];
        curSum[0] = root.val;

        // 递归的看左子树
        if(root.left!=null)
            __dfs(root.left,curSum);
    }

方法2时间和空间都有大幅提升

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值