-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargest_BST.cpp
More file actions
61 lines (49 loc) · 1.1 KB
/
Largest_BST.cpp
File metadata and controls
61 lines (49 loc) · 1.1 KB
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
#include <iostream>
#include<climits>
using namespace std;
class Node{
public:
int data;
Node *left,*right;
Node(int val){
data=val;
left=right=NULL;
}
};
struct Info{
int size;
int max;
int min;
int ans;
bool isBST;
};
Info LargestBSTinBT(Node *root){
if(root==NULL){
return {0,INT_MIN,INT_MAX,0,true};
}
if(root->left ==NULL && root->right==NULL){
return {1,root->data,root->data,1,true};
}
Info LeftInfo=LargestBSTinBT(root->left);
Info rightInfo=LargestBSTinBT(root->right);
Info curr;
curr.size=(1+LeftInfo.size+rightInfo.size);
if(LeftInfo.isBST && rightInfo.isBST && LeftInfo.max <root->data && rightInfo.min>root->data){
curr.min =min(LeftInfo.min,min(rightInfo.min,root->data));
curr.max=max(rightInfo.max,max(LeftInfo.max,root->data));
curr.ans=curr.size;
curr.isBST=true;
return curr;
}
curr.ans=max(LeftInfo.ans,rightInfo.ans);
curr.isBST=false;
return curr;
}
int main(){
Node *root=new Node(15);
root->left=new Node(20);
root->right=new Node(30);
root->left->left=new Node(5);
cout<<"Largest bst in BT : "<< LargestBSTinBT(root).ans<<endl;
return 0;
}