forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Largest_BST_Subtree.cpp
74 lines (67 loc) · 2.41 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// O(n^2)
/*
class Solution {
bool isValidBST(TreeNode* root, long Min, long Max) {
if(!root) return true;
if(!(root->val > Min and root->val < Max)) return false;
return (isValidBST(root->left, Min, root->val) && isValidBST(root->right, root->val, Max));
}
size_t size(TreeNode* root) const {
if(!root) return 0;
return (1 + size(root->left) + size(root->right));
}
public:
int largestBSTSubtree(TreeNode* root) {
if(!root) return 0;
if(isValidBST(root, numeric_limits<long>::min(), numeric_limits<long>::max())) {
return size(root);
}
return max(largestBSTSubtree(root->left), largestBSTSubtree(root->right));
}
};
*/
// O(n)
class Solution {
bool isValidBST(TreeNode* root, long min, long max) {
if(!root) return true;
if(!(root->val > min && root->val < max)) return false;
return (isValidBST(root->left, min, root->val) && isValidBST(root->right, root->val, max));
}
bool largestBSTSubtreeRecur(TreeNode* root, long Min, long Max, int& nodeCnt, int& result) {
if(!root) return true;
int leftNodeCnt = 0, rightNodeCnt = 0;
bool isBST = (root->val > Min and root->val < Max);
isBST &= largestBSTSubtreeRecur(root->left, Min, root->val, leftNodeCnt, result);
isBST &= largestBSTSubtreeRecur(root->right, root->val, Max, rightNodeCnt, result);
nodeCnt = 1 + leftNodeCnt + rightNodeCnt;
if(isBST) {
result = max(result, nodeCnt);
return true;
}
bool isLeftBST = isValidBST(root->left, numeric_limits<long>::min(), numeric_limits<long>::max());
if(isLeftBST) {
result = max(result, leftNodeCnt);
}
bool isRightBST = isValidBST(root->right, numeric_limits<long>::min(), numeric_limits<long>::max());
if(isRightBST) {
result = max(result, rightNodeCnt);
}
return false;
}
public:
int largestBSTSubtree(TreeNode* root) {
int cnt = 0;
int result = 0;
largestBSTSubtreeRecur(root, numeric_limits<long>::min(), numeric_limits<long>::max(), cnt, result);
return result;
}
};