-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargest BST.cpp
26 lines (20 loc) · 879 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
pair<pair<bool,int>,pair<int,int>> traverse(Node* root)
{
if(!root)
return {{1 , 0},{0 , 0}};
if(!root->left && !root->right)
return {{1 , 1} , {root->data , root->data}};
pair<pair<bool,int>,pair<int,int>> p1=traverse(root->left);
pair<pair<bool,int>,pair<int,int>> p2=traverse(root->right);
bool left= (root->left) ? ((p1.second.second < root->data) ? 1 : 0) : 1;
bool right= (root->right) ? ((p2.second.first > root->data) ? 1 : 0) : 1;
int l=(root->left) ? p1.second.first : root->data;
int r=(root->right) ? p2.second.second : root->data;
if(p1.first.first && p2.first.first && left && right)
return {{1 , p1.first.second + p2.first.second + 1} , {l , r}};
return {{0 , max(p1.first.second , p2.first.second)} , {0 , 0}};
}
int largestBst(Node *root)
{
return traverse(root).first.second;
}