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?
int count(TreeNode* root, int lower, int upper) {
if (!root) return 0;
if (root->val <= lower || root->val >= upper) return -1;
int left = count(root->left, lower, root->val);
if (left == -1) return -1;
int right = count(root->right, root->val, upper);
if (right == -1) return -1;
return left + right + 1;
}
void dfs(TreeNode* root, int& res) {
if (!root) return;
int n = count(root, INT_MIN, INT_MAX);
if (n != -1) {
res = max(res, n);
return;
}
dfs(root->left, res);
dfs(root->right, res);
}
int largestBSTSubtree(TreeNode* root) { // time: O(n^2); space: O(n)
int res = 0;
dfs(root, res);
return res;
}Last updated
Was this helpful?