-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
levelOrderTraversalIterative.cpp
98 lines (86 loc) · 1.57 KB
/
levelOrderTraversalIterative.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
/*
* Program to implement level order traversal - iterative version
*/
#include <iostream>
#include <queue.h>
const int maxNodes = 15;
struct Node
{
int data;
Node* left;
Node* right;
};
/*
* An helper function to get a new node
*/
Node* newNode( int data )
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = nullptr;
return temp;
}
/*
* function to insert a new node.
* Arg : root Node, new data
*/
void insert( Node* & node, int data)
{
if ( node == nullptr)
{
node = newNode(data);
}
else
{
if (data < node->data)
{
insert( node->left, data);
}
else
{
insert( node->right, data);
}
}
}
/*
* Level order traversal
*/
void levelOrder( Node * node )
{
std::cout << "Printing level order traversal of the tree:\n";
if ( node == nullptr )
{
std::cout << "Empty tree\n";
return ;
}
algo::Queue<Node*> Q(maxNodes);
Q.push(node);
while ( !Q.empty() )
{
Node *currNode = Q.front();
std::cout << currNode->data << " ";
Q.pop();
if (currNode->left != nullptr)
{
Q.push(currNode->left);
}
if (currNode->right != nullptr)
{
Q.push(currNode->right);
}
}
std::cout << std::endl;
}
int main()
{
Node * root;
insert(root, 4);
insert(root, 2);
insert(root, 6);
insert(root, 1);
insert(root, 3);
insert(root, 5);
insert(root, 7);
levelOrder(root);
return 0;
}