Skip to content

Commit 88f6213

Browse files
authored
Create 333. Largest BST Subtree.cpp
1 parent e8a7aef commit 88f6213

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

C++/333. Largest BST Subtree.cpp

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
int largestBSTSubtree(TreeNode* root) {
13+
int res = 0;
14+
dfs(root, res);
15+
return res;
16+
}
17+
18+
vector<int> dfs(TreeNode* root, int& res){
19+
if(!root) return {INT_MAX, INT_MIN, 0};
20+
auto l = dfs(root->left, res);
21+
auto r = dfs(root->right, res);
22+
int count = (l[2] == -1 || r[2] == -1 || l[1] >= root->val || r[0] <= root->val) ? -1 : l[2] + r[2] + 1;
23+
res = max(res, count);
24+
return {min(root->val, min(l[0], r[0])), max(root->val, max(l[1], r[1])), count};
25+
}
26+
};

0 commit comments

Comments
 (0)