-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplement.cpp
86 lines (76 loc) · 1.14 KB
/
implement.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
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node *left;
node *right;
node(int x){
data = x;
left = NULL;
right = NULL;
}
};
class BinaryTree{
node *root;
public:
BinaryTree(){
root = NULL;
}
//Level order insertion
void insertLevelOrder(int x){
node *temp = new node(x);
if(root == NULL){
root = temp;
return;
}
queue<node *> q;
q.push(root);
while(!q.empty()){
node *cur = q.front();
q.pop();
if(cur->left != NULL){
q.push(cur->left);
}
else{
cur->left = temp;
return;
}
if(cur->right != NULL){
q.push(cur->right);
}
else{
cur->right = temp;
return;
}
}
}
void display_LevelOrder(){
if(root == NULL){
return;
}
queue<node *> q;
q.push(root);
while(!q.empty()){
node *temp = q.front();
q.pop();
if(temp->left != NULL) q.push(temp->left);
if(temp->right != NULL) q.push(temp->right);
cout << temp->data << " ";
}
cout << endl;
}
};
int main()
{
BinaryTree bt;
int n;
cin >> n;
for(int i = 0; i < n; i++){
int x;
cin >> x;
bt.insertLevelOrder(x);
}
bt.display_LevelOrder();
return 0;
}