2021-10-01

这篇博客探讨了如何使用递归方法找到二叉树中最大的二叉搜索树(BST)子树,并提供了Java代码实现。算法通过检查每个节点是否符合BST条件,更新最大BST子树的节点数量。主要涉及二叉树遍历、递归和二叉搜索树的性质。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

333. 最大 BST 子树

思路:这题用递归,如果root是bst树,就返回其节点值,返回时与最大的节点值进行比较,更新最大值,若不是,直接返回-1,需要注意的就是怎么判断这个树是不是bst树,需要那root的值和左子树的最小值以及右子树的最大值进行比较!

class Solution {
    private int maxCount=0;
    public int largestBSTSubtree(TreeNode root) {
        count(root);
        return maxCount;
    }
    public int count(TreeNode root){
        if(root==null) return 0;
        if(root.right==null&&root.left==null){
            maxCount=Math.max(maxCount,1);
            return 1;
        }
        int left=count(root.left);
        int right=count(root.right);
        if(left==-1||right==-1)return -1;
        if(root.left==null&&findMin(root.right)>root.val){
            maxCount=Math.max(maxCount,left+right+1);
            return left+right+1;
        }else if(root.right==null&&findMax(root.left)<root.val){
            maxCount=Math.max(maxCount,left+right+1);
            return left+right+1;
        }else{
            if(root.right!=null&&root.left!=null
                    &&findMin(root.right)>root.val&&findMax(root.left)<root.val){
                maxCount=Math.max(maxCount,left+right+1);
                return left+right+1;
            }
            return -1;
        }
    }
    public int findMax(TreeNode root){
        while(root.right!=null){
            root=root.right;
        }
        return root.val;
    }
    public int findMin(TreeNode root){
        while(root.left!=null){
            root=root.left;
        }
        return root.val;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值