Created
July 28, 2019 18:46
-
-
Save ajinkyajawale14499/5a48d07bf7d86f06fcd9289626635f8b to your computer and use it in GitHub Desktop.
Print level order traversal of Binary Tree using One Queue in o(n)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// code goes here! | |
#include <iostream> | |
#include <queue> | |
using namespace std; | |
// node structure | |
struct Node | |
{ | |
int data; | |
struct Node* left; | |
struct Node* right; | |
}; | |
// Utility function to create new node to binary tree | |
Node* newNode(int data) | |
{ | |
Node* temp = new Node; | |
temp-> data = data; | |
temp-> left = NULL; | |
temp-> right= NULL; | |
return temp; | |
} | |
// LevelOrder using single Queue | |
void LevelOrderQ( Node* root) | |
{ | |
if(root == NULL) return; | |
queue< Node * > q; //create empty Queue | |
q.push(root); //enqueue root | |
while(q.empty() == false) | |
{ | |
// Print front of queue and remove it from queue | |
Node* node = q.front(); | |
cout<< node->data << " "; | |
q.pop(); | |
//enqueue Left child | |
if(node->left != NULL) | |
q.push(node->left); | |
//enqueue right child | |
if(node->right != NULL) | |
q.push(node->right); | |
} | |
} | |
//driver function | |
int main() { | |
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"; | |
LevelOrderQ(root); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment