LeetCode 669. 修剪二叉搜索树 java题解

https://leetcode.cn/problems/trim-a-binary-search-tree/description/
我代码:没利用到树的性质,遍历了每一个节点

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        //遍历所有节点,寻找需要删除的节点
        if(root==null) return null;
        //遍历
        //寻找左右子树中,要删除的节点
        if(root!=null)
            root.left=trimBST(root.left,low,high);
        if(root!=null)
            root.right=trimBST(root.right,low,high);
        if(root!=null){//如果当前节点需要被删除
            if(root.val<low||root.val>high){
                root=delete(root);//删除后的根节点
            }
        }
        return root;
    }
    //删除节点,并保持树结构
    public TreeNode delete(TreeNode root){
        if(root==null) return null;
        if(root.left==null&&root.right==null){
            return null;//叶子结点直接删除
        }
        if(root.left!=null&&root.right==null){
            root=root.left;//用左孩子替代
            return root;
        }
        else if(root.left==null&&root.right!=null){
            root=root.right;//用右孩子替代
            return root;
        }
        else{//左右孩子都不为空
            //把左孩子,放到右子树的最左节点,作为它的左孩子
            TreeNode right_left=find(root.right);
            right_left=root.left;
            root.left=null;
            root=root.right;
            return root;
        }
    }
    public TreeNode find(TreeNode node){
        while(node.left!=null){
            node=node.left;
        }
        return node;
    }
}

参考代码:我进行了注释

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null) {
            return null;
        }
        if (root.val < low) {
        //如果根节点小于左边界,那么根节点和左子树都小于左边界。只需要考虑右子树。
            return trimBST(root.right, low, high);
        }
        //如果根节点大于右边界,那么根节点和右子树都大于右边界。只需要考虑左子树。
        if (root.val > high) {
            return trimBST(root.left, low, high);
        }
        // root在[low,high]范围内,那么需要分别寻找左右子树是否要删除
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
        return root;
    }
}

还有一种迭代法,没有写出来。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值