forked from hbohra98/Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTree_Traversal_levelorder.cpp
More file actions
79 lines (62 loc) · 1.46 KB
/
Tree_Traversal_levelorder.cpp
File metadata and controls
79 lines (62 loc) · 1.46 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
/*
Imp Algorithm
Time complexity : o(n)
Space complexity : Best -> o(1) & Worst -> o(n)
*/
#include<bits/stdc++.h>
using namespace std;
struct Node{
char data;
Node *left;
Node *right;
};
/*
inserting as in binary search tree
*/
Node* Insert(Node *root,char data) {
if(root == NULL) {
root = new Node();
root->data = data;
root->left = root->right = NULL;
}
else if(data <= root->data) root->left = Insert(root->left,data);
else root->right = Insert(root->right,data);
return root;
}
/* Level order traversal */
void levelorder(Node *root){
if(root==NULL)return ;
//queue which store the nodes that are to be visited
queue<Node *> Q;
Q.push(root);
while(!Q.empty()){
Node *current=Q.front();
/*
remove the element as its visited and left and right are
pushed into the queue
*/
Q.pop();
cout << current->data << " ";
/*
push left and right as the traversal is level order and
we have to traverse next level rather than depth
*/
if(current->left!=NULL)Q.push(current->left);
if(current->right!=NULL)Q.push(current->right);
}
}
int main(){
/*
6
/ \
4 7
/ \ \
1 5 9
*/
Node* root = NULL;
//Node* root = NULL;
root = Insert(root,'6'); root = Insert(root,'4');
root = Insert(root,'7'); root = Insert(root,'1');
root = Insert(root,'5'); root = Insert(root,'9');
levelorder(root);
}