-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathlevelorder_tree.cpp
More file actions
78 lines (64 loc) · 1.48 KB
/
levelorder_tree.cpp
File metadata and controls
78 lines (64 loc) · 1.48 KB
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
// C++ program to print level order traversal
// of a Tree
#include <iostream>
#include <queue>
using namespace std;
// A Binary Tree Node
struct node
{
int data;
struct node *left, *right;
};
// 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;
}
// Function to print Level Order Traversal
// of the Binary Tree
void levelorder(node *root)
{
// Base Case
if (root == NULL)
return;
// Create an empty queue for
// level order tarversal
queue<node *> q;
// Enqueue Root and initialize height
q.push(root);
while (q.empty() == false)
{
// Print front of queue and remove
// it from queue
node *tmp = q.front();
cout << tmp->data << " ";
q.pop();
/* Enqueue left child */
if (tmp->left != NULL)
q.push(tmp->left);
/* Enqueue right child */
if (tmp->right != NULL)
q.push(tmp->right);
}
}
// Driver Code
int main()
{
// Create the following Binary Tree
// 1
// / \
// 2 3
// / \
// 4 5
node *root = newnode(1);
root->left = newnode(2);
root->right = newnode(3);
root->left->left = newnode(4);
root->left->right = newnode(5);
cout << "Level Order traversal of binary tree is \n";
levelorder(root);
return 0;
}