forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlargest-bst-subtree.cpp
58 lines (53 loc) · 1.95 KB
/
largest-bst-subtree.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
48
49
50
51
52
53
54
55
56
57
58
// Time: O(n)
// Space: O(h)
/**
* 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) {
if (!root) {
return 0;
}
int max_size = 1;
largestBSTSubtreeHelper(root, &max_size);
return max_size;
}
private:
tuple<int, int, int> largestBSTSubtreeHelper(TreeNode* root, int *max_size) {
if (!root->left && !root->right) {
return make_tuple(1, root->val, root->val);
}
if (!root->left) {
int size, min_val, max_val;
tie(size, min_val, max_val) = largestBSTSubtreeHelper(root->right, max_size);
if (size > 0 && root->val < min_val) {
*max_size = max(*max_size, 1 + size);
return make_tuple(1 + size, root->val, max_val);
}
} else if (!root->right) {
int size, min_val, max_val;
tie(size, min_val, max_val) = largestBSTSubtreeHelper(root->left, max_size);
if (size > 0 && max_val < root->val) {
*max_size = max(*max_size, 1 + size);
return make_tuple(1 + size, min_val, root->val);
}
} else {
int left_size, left_min, left_max, right_size, right_min, right_max;
tie(left_size, left_min, left_max) = largestBSTSubtreeHelper(root->left, max_size);
tie(right_size, right_min, right_max) = largestBSTSubtreeHelper(root->right, max_size);
if (left_size > 0 && right_size > 0 &&
left_max < root->val && root->val < right_min) {
*max_size = max(*max_size, 1 + left_size + right_size);
return make_tuple(1 + left_size + right_size, left_min, right_max);
}
}
return make_tuple(0, root->val, root->val);
}
};