-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlevelordertraversal.cpp
38 lines (37 loc) · 1.01 KB
/
levelordertraversal.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
#include <queue>
// ----------------------- utility function level order traversal
int height(node *root ){
if(root==NULL) return 0;
return 1+ max(height(root-> left) , height(root->right));
}
void printq(queue<node*> q){
queue<node*> qcopy = q;
cout<<"\n print Queue ";
while(!qcopy.empty()){
cout << " \t " << qcopy.front();
qcopy.pop();
}
cout << '\n';
}
void levelordertraversal(node* root, int i , int orderarr[]){
int h = height(root);
cout << " height "<< h << endl;
if(root == NULL ) return;
queue<node*> q; // empty queue
node* curr; // node to store front element
q.push(root);
q.push(NULL);
while(q.size()>1){
curr = q.front();
q.pop();
if(curr ==NULL){
q.push(NULL);
cout << "\n";
}else{
if(curr->left) q.push(curr->left);
if(curr->right) q.push(curr->right);
cout << curr->data << " " ; orderarr[i]=curr->data; i++;
}
}
printq(q);
}