Skip to content

Instantly share code, notes, and snippets.

@ajinkyajawale14499
Created July 28, 2019 18:46
Show Gist options
  • Save ajinkyajawale14499/5a48d07bf7d86f06fcd9289626635f8b to your computer and use it in GitHub Desktop.
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)
// 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