-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargest BST.cpp
38 lines (33 loc) · 1008 Bytes
/
Largest BST.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
struct Info{
int min;
int max;
int size;
bool isBST;
int answer;
};
Info _largestBST(Node*);
int largestBst(Node *root){
return _largestBST(root).answer;
}
Info _largestBST(Node *root){
if(root == nullptr)
return {INT_MAX, INT_MIN, 0, true, 0};
else if(root->left == nullptr && root->right == nullptr)
return {root->data, root->data, 1, true, 1};
else{
Info linfo = _largestBST(root->left);
Info rinfo = _largestBST(root->right);
Info temp;
temp.size = linfo.size + rinfo.size + 1;
if(linfo.isBST && rinfo.isBST && linfo.max <= root->data && root->data <= rinfo.min){
temp.answer = temp.size;
temp.min = min({root->data, linfo.min, rinfo.min});
temp.max = max({root->data, linfo.max, rinfo.max});
temp.isBST = true;
return temp;
}
temp.answer = max(linfo.answer, rinfo.answer);
temp.isBST = false;
return temp;
}
}