-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Tree Construction.cpp
More file actions
167 lines (146 loc) · 2.32 KB
/
Copy pathBinary Tree Construction.cpp
File metadata and controls
167 lines (146 loc) · 2.32 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
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
/*
Tree Construction
Time Complexity: O(N^2)/O(N^3)
*/
#include <bits/stdc++.h>
using namespace std;
struct Node
{
Node* left;
Node* right;
string data;
Node(string x)
{
left = NULL;
right = NULL;
data = x;
}
};
void preOrder(Node* root)
{
if(root)
{
cout<<root->data<<" ";
preOrder(root->left);
preOrder(root->right);
}
}
void inOrder(Node* root)
{
if(root)
{
inOrder(root->left);
cout<<root->data<<" ";
inOrder(root->right);
}
}
void postOrder(Node* root)
{
if(root)
{
postOrder(root->left);
postOrder(root->right);
cout<<root->data<<" ";
}
}
void levelOrder(Node* root)
{
if(root)
{
queue <Node*> Q;
Q.push(root);
while(!Q.empty())
{
Node* temp = Q.front();
if(temp->left)
{
Q.push(temp->left);
}
if(temp->right)
{
Q.push(temp->right);
}
cout<<temp->data<<" ";
Q.pop();
}
}
}
int find_element(string str[], string val, int l, int r)
{
for(int i = l; i<r; i++)
{
if(str[i] == val)
{
return i;
}
}
return -1;
}
Node* pre_in(string pre[], string in[], int l, int r)
{
static int preIndex = 0;
if(l>=r)
{
return NULL;
}
else
{
Node* root = new Node(pre[preIndex]);
preIndex++;
int i = find_element(in, root->data, l, r);
root->left = pre_in(pre, in, l, i);
root->right = pre_in(pre, in, i+1, r);
return root;
}
}
Node* in_lev(string in[], string lev[], int l, int r, int N)
{
if(l>=r)
{
return NULL;
}
else
{
int i;
for(int n = 0; n<N; n++)
{
i = find_element(in, lev[n], l, r);
if(i != -1)
{
break;
}
}
Node* root = new Node(in[i]);
root->left = in_lev(in, lev, l, i, N);
root->right = in_lev(in, lev, i+1, r, N);
return root;
}
}
int main()
{
int N;
cin>>N;
string S[4][N];
string order[4] = { "PreOrder Traversal: ",
"InOrder Traversal: ",
"PostOrder Traversal: ",
"LevelOrder Traversal: "};
for(int m = 0; m<4; m++)
{
for(int n = 0; n<N; n++)
{
cin>>S[m][n];
}
}
// Node* root = pre_in(S[0], S[1], 0, N);
Node* root = in_lev(S[1], S[3], 0, N, N);
preOrder(root);
cout<<endl;
inOrder(root);
cout<<endl;
postOrder(root);
cout<<endl;
levelOrder(root);
cout<<endl;
return 0;
}