forked from anmol098/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
levelOrderTraversalRecursive.cpp
96 lines (86 loc) · 1.54 KB
/
levelOrderTraversalRecursive.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
/*
* Level order BST traveral iterative
*/
#include <iostream>
struct Node
{
int data;
Node *left;
Node *right;
};
Node* newNode( int data )
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = nullptr;
return temp;
}
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);
}
}
}
int height( const Node * node)
{
if ( node == nullptr )
{
return 0;
}
else
{
int leftHeight = height(node->left);
int rightHeight = height(node->right);
return ( 1 + ((leftHeight > rightHeight) ? leftHeight : rightHeight));
}
}
void printLevel(Node *node, int level)
{
if (node == nullptr)
{
return;
}
if ( level == 1 )
{
std::cout << node->data <<" ";
}
else
{
printLevel( node->left, level - 1);
printLevel( node->right, level - 1);
}
}
void levelOrder( Node * node )
{
std::cout << "Level order traversal of the tree:\n";
int h = height(node);
for ( int i = 1; i <= h; ++i ) {
printLevel(node, i );
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;
}