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)
易错点
- 回传区间要左右取一下min和max:为了deal with 底端传回来的dummy区间。
- 如图总结了一下从上至下和从下至上检查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};
}
}
};