-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlargestBSTinBT.cpp
More file actions
65 lines (59 loc) · 1.37 KB
/
largestBSTinBT.cpp
File metadata and controls
65 lines (59 loc) · 1.37 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
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return(node);
}
struct Node* insert(struct Node* root, int x) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node*));
temp->data = x;
temp->left = NULL;
temp->right = NULL;
if(root == NULL) {
root = temp;
}
else if(x <= root->data) {
root->left = insert(root->left, x);
} else {
root->right = insert(root->right, x);
}
return root;
}
struct bst {
bool isBST;
int size;
int min;
int max;
};
bst largestBST(Node* root) {
if(root == NULL) {
bst b = {true,0,INT_MAX,INT_MIN};
return b;
}
bst l = largestBST(root->left);
bst r = largestBST(root->right);
if(l.isBST && r.isBST && l.max < root->data && r.min > root->data) {
bst b = {true,1+r.size+l.size,min(l.min,root->data),max(r.max,root->data)};
return b;
} else {
bst b = {false,max(l.size, r.size),-1,-1};
return b;
}
}
int main() {
struct Node *root = newNode(60);
root->left = newNode(65);
root->right = newNode(70);
root->left->left = newNode(50);
bst ans = largestBST(root);
cout<<ans.size<<endl;
}