-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlc333
33 lines (33 loc) · 1.18 KB
/
lc333
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int largestBSTSubtree(TreeNode* root) {
int res = 0, mn = INT_MIN, mx = INT_MAX;
isValidBST(root, mn, mx, res);
return res;
}
void isValidBST(TreeNode* root, int& mn, int& mx, int& res) {
if (!root) return;
int left_cnt = 0, right_cnt = 0, left_mn = INT_MIN;
int right_mn = INT_MIN, left_mx = INT_MAX, right_mx = INT_MAX;
isValidBST(root->left, left_mn, left_mx, left_cnt);
isValidBST(root->right, right_mn, right_mx, right_cnt);
if ((!root->left || root->val > left_mx) && (!root->right || root->val < right_mn)) {
res = left_cnt + right_cnt + 1;
mn = root->left ? left_mn : root->val;
mx = root->right ? right_mx : root->val;
} else {
res = max(left_cnt, right_cnt);
}
}
};