LeetCode 669 修剪二叉搜索树

在这里插入图片描述

原题链接

  1. 如下
  2. 递归。。。。。。
  3. 二刷:经典的递归方法,假设递归函数能解决某个问题
  4. 在不同情况下调用递归函数,传入的限定条件 low 和 high 是不变的
    本题是修剪二叉搜索树,与LeetCode 450 删除二叉搜索树不同
    在这里插入图片描述
    在这里插入图片描述
class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        //递归 截止条件
        if(root == null) return null;
        if(root.val < low){
            root = root.right;
            return trimBST(root, low, high);
        }else if(root.val > high){
            root = root.left;
            return trimBST(root, low, high);
        }else{
            root.left = trimBST(root.left, low, high);
            root.right = trimBST(root.right, low, high);
            return root;
        }
        // return root;
    }
}


class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null) {
            return null;
        }
        if (root.val < low) {
            //因为是二叉搜索树,节点.left < 节点 < 节点.right
            //节点数字比low小,就把左节点全部裁掉.
            root = root.right;
            //裁掉之后,继续看右节点的剪裁情况.剪裁后重新赋值给root.
            root = trimBST(root, low, high);
        } else if (root.val > high) {
            //如果数字比high大,就把右节点全部裁掉.
            root = root.left;
            //裁掉之后,继续看左节点的剪裁情况
            root = trimBST(root, low, high);
        } else {
            //如果数字在区间内,就去裁剪左右子节点.
            root.left = trimBST(root.left, low, high);
            root.right = trimBST(root.right, low, high);
        }
        return root;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值