-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestBSTinBT.cpp
More file actions
66 lines (50 loc) · 1.33 KB
/
LargestBSTinBT.cpp
File metadata and controls
66 lines (50 loc) · 1.33 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
62
63
64
65
66
#include<iostream>
#include<climits>
using namespace std;
struct Node{
int data;
Node* right;
Node* left;
Node(int val){
right = NULL;
left = NULL;
data = val;
}
};
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<<largestBSTinBT(root).ans<<endl;
return 0;
}