-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathLevel Order Tree Traversal.cpp
111 lines (85 loc) · 2.06 KB
/
Level Order Tree Traversal.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *left, *right;
};
int level =0;
bool flag= true;
void printLevelOrder(Node *root)
{
if (root == NULL)
return;
queue<Node *> q;
stack<Node *>s;
q.push(root);
while (!q.empty())
{
int sa = q.size();
level++;
while(sa--)
{
Node *node = q.front();
q.pop();
if(flag)
cout <<node->data<<" " ;
else
s.push(node);
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
}
if(!flag)
{
while(!s.empty())
{
Node* ptr=s.top();
s.pop();
cout<<ptr->data<<" ";
}
}
if(level==2)
{
flag =!flag;
level=0;
}
cout<<endl;
}
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in above diagram
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->left->left->right = newNode(9);
root->left->right->left = newNode(3);
root->left->right->right = newNode(1);
root->right->left->left = newNode(4);
root->right->left->right = newNode(2);
root->right->right->left = newNode(7);
root->right->right->right = newNode(2);
root->left->right->left->left = newNode(16);
root->left->right->left->right = newNode(17);
root->right->left->right->left = newNode(18);
root->right->right->left->right = newNode(19);
cout << "Level Order traversal of binary tree is \n";
printLevelOrder(root);
return 0;
}