代码随想录训练营第23天|669. 修剪二叉搜索树,108.将有序数组转换为二叉搜索树,538.把二叉搜索树转换为累加树

代码随想录训练营第23天|669. 修剪二叉搜索树,108.将有序数组转换为二叉搜索树,538.把二叉搜索树转换为累加树


)

669.修剪二叉搜索树

文章

代码随想录|0669.修剪二叉搜索树

思路

看完题不太会
难点在于
1)如何搜索上下界
2)如何删除

代码随想录提供了两种做法
1)递归,如果根节点在区间内,则修剪左右子树;如果根节点值小于区间下确界,则返回左子树的修剪;如果根节点值大于区间上确界,则返回右子树的修剪。如果根节点为空则返回空。
2)迭代。首先移动root,使得root位于区间内。然后从根节点出发找下界,即如果发现当前节点的左孩子的值小于下界,则用左孩子的右孩子代替左孩子,直到当前的左孩子在区间内,才能更新当前的访问位置为左孩子。向右找上界同理。最终返回root。

代码

迭代法好理解,这里放迭代法

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        TreeNode cur;
        while (root != null && (root.val > high || root.val < low)) {
            if (root.val > high) {
                root = root.left;
            } else {
                root = root.right;
            }
        }
        cur = root;
        while (cur != null) {
            while (cur.left != null && cur.left.val < low) {
                cur.left = cur.left.right;
            }
            cur = cur.left;
        }
        cur = root;
        while (cur != null) {
            while (cur.right != null && cur.right.val > high) {
                cur.right = cur.right.left;
            }
            cur = cur.right;
        }
        return root;
    }
}

108.将有序数组转换为二叉搜索树

文章

代码随想录|0108.将有序数组转换为二叉搜索树

思路

要求是平衡二叉搜索树
考虑从数组中间取根节点,递归用两侧数组分别构造左右子树

代码

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        int n = nums.length;
        return construct(nums, 0, n);
    }
    public TreeNode construct(int[] nums, int start, int end) {
        if (start < end) {
            int mid = start + ((end - start) >> 1);
            TreeNode root = new TreeNode(nums[mid]);
            root.left = construct(nums, start, mid);
            root.right = construct(nums, mid + 1, end);
            return root;
        } else{
            return null;
        }
    }
}

538.把二叉搜索树转换为累加树

文章

代码随想录|0538.把二叉搜索树转换为累加树

思路

得到了双指针法的提示,不然也不容易想到
这是先右后左的中序遍历,全局变量指针pre维护上一个累加过的节点,递归中序遍历,将累加过的节点的值加到当前节点值上

代码

class Solution {

    private TreeNode pre = null;

    public TreeNode convertBST(TreeNode root) {
        traversal(root);
        return root;
    }
    public void traversal(TreeNode root) {
        if (root == null) {
            return;
        }
        traversal(root.right);
        if (pre != null) {
            root.val += pre.val;
        }
        pre = root;
        traversal(root.left);
    }
}

总结

不出意外的话是二叉树最后一天
感觉遍历二叉树仿佛是一切的基础
又要做题又要开会真的缺时间总结

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值