-
Notifications
You must be signed in to change notification settings - Fork 105
/
LargestBstSubtree.cpp
128 lines (100 loc) · 2.26 KB
/
LargestBstSubtree.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
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data=0;
Node *left = nullptr;
Node *right = nullptr;
Node(int data)
{
this->data = data;
}
};
class Pair {
public:
Node *node=nullptr;
int state=0;
Pair(Node *node, int state) {
this->node = node;
this->state = state;
}
};
int idx = 0;
Node *constructTree(vector<int> &arr)
{
if (idx == arr.size() || arr[idx] == -1)
{
idx++;
return nullptr;
}
Node *node = new Node(arr[idx++]);
node->left = constructTree(arr);
node->right = constructTree(arr);
return node;
}
void display(Node *node)
{
if (node == nullptr)
return;
string str = "";
str += node->left != nullptr ? to_string(node->left->data) : ".";
str += " <- " + to_string(node->data) + " -> ";
str += node->right != nullptr ? to_string(node->right->data) : ".";
cout << str << endl;
display(node->left);
display(node->right);
}
int height(Node *node)
{
return node == nullptr ? -1 : max(height(node->left), height(node->right)) + 1;
}
class pentapair
{
public:
int size=0;
Node* root=NULL;
int max=INT_MIN;
int min=INT_MAX;
bool isbst=true;
};
pentapair* labst(Node* node){
if(node==NULL){
return new pentapair();
}
pentapair* l =labst(node->left);
pentapair* r= labst(node->right);
pentapair* ans= new pentapair();
bool atnode=(l->max<node->data) && (r->min>node->data);
ans->isbst=((l->isbst==true) && (r->isbst==true) && (atnode==true)) ? true:false;
ans->min=min(l->min,min(r->min,node->data));
ans->max=max(l->max,max(r->max,node->data));
if(ans->isbst==true){
ans->size=l->size+r->size+1;
ans->root=node;
}
else{
ans->size=max(l->size,r->size);
ans->root=l->size>r->size ? l->root : r->root;
}
return ans;
}
int main(){
int n;
cin>>n;
vector<int> arr(n,0);
for(int i = 0; i < n; i++) {
string tmp;
cin>>tmp;
if (tmp=="n") {
arr[i] = -1;
} else {
arr[i] = stoi(tmp);
}
}
Node *root = constructTree(arr);
pentapair* r = labst(root);
cout<<r->root->data<<"@"<<r->size;
}