-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary sub tress in a tree.cpp
182 lines (161 loc) · 2.52 KB
/
binary sub tress in a tree.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
//Q6: Given an integer n, return at most n + 1 OR maximum unique BST's (binary search trees), which have exactly n nodes of unique values from 1 to n. Return the answer in any order.
//Example (For n = 3)
#include<iostream>
using namespace std;
class Node{
public:
int val;
Node *r;
Node *l;
Node *next;
Node()
{
val=0;
r=NULL;
l=NULL;
next=NULL;
}
Node(int x)
{
val=x;
r=NULL;
l=NULL;
next=NULL;
}
};
class queue{
public:
Node *head;//front
Node *tail;//rear
queue()
{
head=NULL;
tail=NULL;
}
void push(Node *& n)
{
if(head==NULL)
{
head=n;
tail=n;
}
else{
head->next=n;
head=n;
}
}
Node* pop()//dequeue at tail
{
Node *temp = tail;
tail = tail->next;
return temp;
}
bool isempty()
{
if(head==NULL && tail==NULL)
{
return true;
}
return false;
}
};
class tree
{
public:
Node *root;
int minv=-999;
int maxv=999;
tree()
{
root=NULL;
}
void insert(int ne)
{
Node *n=new Node(ne);
queue q;
if(root==NULL)
{
root=n;
}
else
{
q.push(root);
while(!q.isempty())
{
Node *temp=q.pop();
if(temp->l!=NULL)
{
q.push(temp->l);
}
else
{
temp->l=n;
return;
}
if(temp->r!=NULL)
{
q.push(temp->r);
}
else
{
temp->r=n;
return;
}
}
}
}
int H(Node *head)
{
if(head==NULL)
{
return -1;
}
else
{
return max(H(head->l),H(head->r))+1;
}
}
void display(Node *t)
{
if(t==NULL)
{
return;
}
cout<<t->val<<" ";
display(t->l);
display(t->r);
}
bool bst(Node *n, int min, int max, int num)
{
if(n==NULL || num==0)
{
return true;
}
if(n->val>=min || n->val<=max)
{
display(n);
cout<<endl;
return bst(n->l, min, n->val,num-1) && bst(n->r, n->val,max,num-1);
}
return false;
}
};
main()
{
tree t;
int n;
cout<<"\nN: ";
cin>>n;
for(int i=1;i<n+1;i++)
{
t.insert(i);
}
t.display(t.root);
cout<<endl;
cout<<"subtrees:";
t.bst(t.root,t.minv,t.maxv,n+1);
cout<<"lst subtrees:";
t.bst(t.root->l,t.minv,t.maxv,n+1);
cout<<"\nrst subtrees:"<<endl;
t.bst(t.root->r,t.minv,t.maxv,n+1);
}