forked from IOSD/IOSD-NITK-HacktoberFest-Meetup-2019
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst.cpp
More file actions
75 lines (74 loc) · 1.7 KB
/
bst.cpp
File metadata and controls
75 lines (74 loc) · 1.7 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
#include<iostream>
#include<queue>
using namespace std;
struct node{
int data;
node * left;
node * right;
node(int data){
this->data = data;
left = right = NULL;
}
};
void addElement(node *& root,int data){
if(!root){
root = new node(data);
return;
}
node * it = root;
node * prev = NULL;
while(it){
prev = it;
if(it->data > data){
it = it->left;
}else{
it = it->right;
}
}
if(prev->data > data){
prev->left = new node(data);
}else{
prev->right = new node(data);
}
return;
}
void printLevelWisePrint(node * root){
queue<node *>q1;
queue<node *>q2;
q1.push(root);
while(!q1.empty() || !q2.empty()){
while(!q1.empty()){
node * top = q1.front();
q1.pop();
cout<<top->data<<" ";
if(top->left){
q2.push(top->left);
}
if(top->right){o
q2.push(top->right);
}
}
cout<<endl;
while(!q2.empty()){
node * top = q2.front();
q2.pop();
cout<<top->data<<" ";
if(top->left){
q1.push(top->left);
}
if(top->right){
q1.push(top->right);
}
}
cout<<endl;
}
}
v
int main(){
node * root = NULL;
addElement(root,8);addElement(root,3);addElement(root,10);
addElement(root,1);addElement(root,6);addElement(root,14);
addElement(root,13);addElement(root,4);addElement(root,7);
addElement(root,2);
printLevelWisePrint(root);
}