[Leetcode] 333. Largest BST Subtree 解题报告

本文介绍了一种使用深度优先搜索解决寻找二叉树中最大二叉搜索树子树的方法,并探讨了如何通过递归获取子树的最大和最小值来判断是否符合二叉搜索树的条件。

摘要生成于 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.
Here's an example:

    10
    / \
   5  15
  / \   \ 
 1   8   7
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?

思路

一道bottom-up的深度优先搜索题目,也就是首先判断左右子树分别是不是合法的BST。如果是的话,我们还需要哪些信息呢?首先是需要知道左右子树的范围,因为我们要判断当前结点为根的树是否为二叉搜索树,就要满足当前结点大于左子树的最大值,并且小于右子树的最小值。其次我们还需要分别知道其左右子树上的最大合法BST的大小。有了这些信息,就可以判断以当前结点为根的二叉树是否为二叉搜索树了。

实现过程中有个小技巧,就是让DFS返回vector<int>。我原来传入了三个int的引用,写的代码又臭又长。。。

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int largestBSTSubtree(TreeNode* root) {
        int ans = 0;
        DFS(root, ans);
        return ans;
    }
private:
    vector<int> DFS(TreeNode *root, int &ans) {
        if (!root) {
            return vector<int>{0, INT_MAX, INT_MIN};
        }
        vector<int> left = DFS(root->left, ans);
        vector<int> right = DFS(root->right, ans);
        if (root->val > left[2] && root->val < right[1]) {
            int min_value = min(root->val, left[1]);
            int max_value = max(root->val, right[2]);
            ans = max(ans, left[0] + right[0] + 1);
            return vector<int>{left[0] + right[0] + 1, min_value, max_value};
        }
        return vector<int> {0, INT_MIN, INT_MAX};
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值