File tree 1 file changed +61
-0
lines changed
1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* C++ program to print level order traversal using STL */
2
+ #include < bits/stdc++.h>
3
+ using namespace std ;
4
+
5
+ // A Binary Tree Node
6
+ struct Node
7
+ {
8
+ int data;
9
+ struct Node *left, *right;
10
+ };
11
+
12
+ // Iterative method to find height of Binary Tree
13
+ void printLevelOrder (Node *root)
14
+ {
15
+ // Base Case
16
+ if (root == NULL ) return ;
17
+
18
+ // Create an empty queue for level order traversal
19
+ queue<Node *> q;
20
+
21
+ // Enqueue Root and initialize height
22
+ q.push (root);
23
+
24
+ while (q.empty () == false )
25
+ {
26
+ // Print front of queue and remove it from queue
27
+ Node *node = q.front ();
28
+ cout << node->data << " " ;
29
+ q.pop ();
30
+
31
+ /* Enqueue left child */
32
+ if (node->left != NULL )
33
+ q.push (node->left );
34
+
35
+ /* Enqueue right child */
36
+ if (node->right != NULL )
37
+ q.push (node->right );
38
+ }
39
+ }
40
+
41
+ // create a new tree node
42
+ Node* newNode (int data)
43
+ {
44
+ Node *temp = new Node;
45
+ temp->data = data;
46
+ temp->left = temp->right = NULL ;
47
+ return temp;
48
+ }
49
+
50
+ int main ()
51
+ {
52
+ Node *root = newNode (1 );
53
+ root->left = newNode (2 );
54
+ root->right = newNode (3 );
55
+ root->left ->left = newNode (4 );
56
+ root->left ->right = newNode (5 );
57
+
58
+ cout << " Level Order traversal of binary tree is \n " ;
59
+ printLevelOrder (root);
60
+ return 0 ;
61
+ }
You can’t perform that action at this time.
0 commit comments