333. Largest BST Subtree


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?

方法0:

思路:

根据hint:You can recursively use algorithm similar to 98. Validate Binary Search Tree at each node of the tree, which will result in O(nlogn) time complexity. 可以在每个节点调取isValidBST。

Complexity

Time complexity: O(n^2)
Space complexity: O(h)

方法1: dfs

思路:

postorder,要求左右子树各返回一个vector,一个lb,一个ub, 一个count,代表了他们子树中的数字范围及count。再传递一个global变量来accumulate size for valid bst。当获取左右回传值之后,根据(lb, ub)来判断root是否也是一个valid bst。怎么判断呢?要求left.up < root -> val < right.lb。如果满足的话,返回一个update的区间,和left.count + right.count + 1。这个区间的含义在这里传达的是,子树的区间范围,所以靠(min(left.lb, root -> val), max(right.ub, root -> val)) 来决定。之所以有min,max只是为了deal with底端,实际上回传的合法区间一定是左右的融合。而如果判断为非法bst之后,我们回传一个不可能被满足的区间(INT_MIN, INT_MAX),这样阻止了count进一步增长,一直保持不变的被传递回主函数。

Complexity

Time complexity: O(n)
Space complexity: O(h)

易错点

  1. 回传区间要左右取一下min和max:为了deal with 底端传回来的dummy区间。
  2. 如图总结了一下从上至下和从下至上检查bst的两种方法。
    在这里插入图片描述
/**
 * 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 result = 0;
        bstHelper(root, result);
        return result;
    }
    
    vector<int> bstHelper(TreeNode* root, int & result) {
        if (!root) return {INT_MAX, INT_MIN, 0};
        
        auto left = bstHelper(root -> left, result);
        auto right = bstHelper(root -> right, result);
        
        if (left[1] < root -> val && root -> val < right[0]) {
            result = max(result, left[2] + right[2] + 1);
            return {min(root -> val, left[0]), max(root -> val, right[1]), left[2] + right[2] + 1};
        }
        else {
            return {INT_MIN, INT_MAX, 0};
        }
    } 
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值