-
Notifications
You must be signed in to change notification settings - Fork 3
/
333.cpp
47 lines (47 loc) · 1.34 KB
/
333.cpp
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* 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 res = 0;
vector<int> dfs(TreeNode* node) {
if (node == nullptr) return {INT_MIN, INT_MAX, 0};
vector<int> curr = {node->val, node->val, 1};
vector<int> left = dfs(node->left);
vector<int> right = dfs(node->right);
if (node->left) {
if (left[2] == -1) return {node->val, node->val, -1};
if (node->val > left[1]) {
curr[0] = left[0];
curr[2] += left[2];
}
else {
curr[2] = -1;
}
}
if (node->right) {
if (right[2] == -1) return {node->val, node->val, -1};
if (node->val < right[0]) {
curr[1] = right[1];
curr[2] += right[2];
}
else {
curr[2] = -1;
}
}
res = max(res, curr[2]);
return curr;
}
int largestBSTSubtree(TreeNode* root) {
dfs(root);
return res;
}
};