-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathBinarySearchTree.cpp
174 lines (159 loc) · 3.04 KB
/
BinarySearchTree.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
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
struct node
{
int data;
node *left,*right;
};
node *root; //root node
void insert(int data) //To insert the data into the tree
{
node *temp=new node;
temp->data=data;
node *temp1,*cur;
if(root==NULL)
{
root=temp;
return;
}
temp1=root;
while(temp1!=NULL)
{
cur=temp1;
if(data < temp1->data)
{
temp1=temp1->left;
if(temp1==NULL)
{
cur->left=temp;
}
}
else
{
temp1=temp1->right;
if(temp1==NULL)
{
cur->right=temp;
}
}
}
}
void preorder() //Iterative preorder traversal
{
cout<<"Preorder\n";
stack<node*>ans;
ans.push(root);
while(!ans.empty())
{
node *cur=ans.top();
ans.pop();
cout<<cur->data<<" ";
if(cur->right)
{
ans.push(cur->right);
}
if(cur->left)
{
ans.push(cur->left);
}
}
cout<<endl;
}
void postorder() //Iterative postorder travsersal
{
cout<<"Postorder\n";
stack<node*> s;
s.push(root);
stack<int>ans;
while (!s.empty())
{
node* curr = s.top();
s.pop();
ans.push(curr->data);
if(curr->left)
{
s.push(curr->left);
}
if(curr->right)
{
s.push(curr->right);
}
}
while (!ans.empty())
{
cout<<ans.top()<< " ";
ans.pop();
}
cout<<endl;
}
void inorder() //Iterative inorder traversal
{
cout<<"\nInorder\n";
stack<node*>s;
node *temp=root;
while( temp || !s.empty())
{
while(temp!=NULL)
{
s.push(temp);
temp=temp->left;
}
temp=s.top();
s.pop();
cout<<temp->data<<" ";
temp=temp->right;
}
cout<<endl;
}
void rec_inorder(node *root) //Recurive inorder traversal
{
if(root!=NULL)
{
rec_inorder(root->left);
cout<<root->data<<" ";
rec_inorder(root->right);
}
}
void rec_preorder(node *root) //Recursive preorder traversal
{
if(root!=NULL)
{
cout<<root->data<<" ";
rec_preorder(root->left);
rec_preorder(root->right);
}
}
void rec_postorder(node *root) //recursive postorder traversal
{
if(root!=NULL)
{
rec_postorder(root->left);
rec_postorder(root->right);
cout<<root->data<<" ";
}
}
int main()
{
int n; //No of inputs
cin>>n;
while(n--)
{
int val;
cin>>val;
insert(val);
}
cout<<"Recurive postorder traversal\n";
rec_postorder(root);
cout<<endl;
postorder();
cout<<"Recurive preorder traversal\n";
rec_preorder(root);
cout<<endl;
preorder();
cout<<"Recurive inorder traversal\n";
rec_inorder(root);
inorder();
cout<<endl;
}