LeetCode 333 - Largest BST Subtree

本文介绍了一种在二叉树中查找最大二叉搜索树子树的方法,通过递归算法,考虑了节点的所有后代,实现了O(n)的时间复杂度。

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

题目描述:

Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.

Note:
A subtree must include all of its descendants.

Example:

Input: [10,5,15,1,8,null,7]

   10 
   / \ 
  5  15 
 / \   \ 
1   8   7

Output: 3
Explanation: The Largest BST Subtree in this case is the highlighted one.
             The return value is the subtree's size, which is 3.

Follow up:
Can you figure out ways to solve it with O(n) time complexity?

class Solution {
public:
    int largestBSTSubtree(TreeNode* root) {
        return maxNum(root)[0];
    }
    
    vector<int> maxNum(TreeNode* root)
    {   // 返回的数组中有三个数,分别是当前节点中的最大BST节点数,当前所有节点的最大值,当前所有节点的最小值
        // 当节点为空的时候,将最大值设为INT_MIN,最小值设为INT_MAX
        // 这样是为了保证其他节点把它作为左节点时,left_max=INT_MIN
        // 其他节点把它作为右节点时,right_min=INT_MAX,都可以组成BST
        if(root==NULL) return {0,INT_MIN,INT_MAX};
        vector<int> left=maxNum(root->left);
        vector<int> right=maxNum(root->right);
        int left_num=left[0], left_max=left[1], left_min=left[2];
        int right_num=right[0], right_max=right[1], right_min=right[2];
        
        if(root->left==NULL&&root->right==NULL) return {1,root->val,root->val};
        else if(root->left!=NULL&&root->right==NULL&&root->val>left_max)
            return {left_num+1,root->val,left_min};
        else if(root->left==NULL&&root->right!=NULL&&root->val<right_min)
            return {right_num+1,right_max,root->val};
        else if(root->left!=NULL&&root->right!=NULL&&root->val<right_min&&root->val>left_max)
            return {left_num+right_num+1,right_max,left_min};
        // 当无法形成BST时,设置最大值为INT_MAX,最小值为INT_MIN,
        // 如果其他节点把它作为左节点,left_max=INT_MAX,如果其他节点把它作为右节点,right_min=INT_MIN,
        // 这样之后的任何节点都不可能和当前节点组成BST
        else return {max(left_num,right_num),INT_MAX,INT_MIN}; 
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值