-
Notifications
You must be signed in to change notification settings - Fork 4
/
level_by_level_printing_using_one_queue.C
61 lines (57 loc) · 1.13 KB
/
level_by_level_printing_using_one_queue.C
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
//author @ Ayush Aggarwal
//Level by level printing of a binary tree using one queues
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
node *left,*right;
};
struct node* newnode(int data)
{
node *temp = new node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
void levelBylevel(node *root)
{
if(root==NULL)
return;
queue <node*> q;
q.push(root);
q.push(NULL);
while(!q.empty())
{
root = q.front();
q.pop();
if(root!=NULL)
{
cout<<root->data<<" ";
if(root->left)
q.push(root->left);
if(root->right)
q.push(root->right);
}
else
{
if(!q.empty())
{
cout<<endl;
q.push(NULL);
}
}
}
}
int main()
{
struct node *root = newnode(10);
root->left = newnode(8);
root->right = newnode(2);
root->left->left = newnode(3);
root->left->right = newnode(5);
root->right->left = newnode(2);
levelBylevel(root);
return 0;
}