Levelorder Traversal

 In this with the help of queue we print element from left to right. We move from one level to the next & store left node element until it becomes NULL & then right node element.


#include<bits/stdc++.h>
using namespace std;

class Node
{
  public:
  int data;
  Node *left,*right;
};

Node *createNode(int new_data)
{
  Node *new_node = new Node();
  new_node->data = new_data;
  new_node->left = NULL;
  new_node->right = NULL;
  return new_node;
}

void levelOrder(Node *root)
{
  if(root == NULL) return;

  queue<Node*> q;
  q.push(root);

  while(q.empty() == false)
  {
    Node *node = q.front();
    cout << node->data << " ";
    q.pop();
    
    if(node->left != NULL) q.push(node->left);
    if(node->right != NULL) q.push(node->right);
  }
}

int main()
{
  Node *root = createNode(5);
  root->left = createNode(9);
  root->right = createNode(11);

  root->left->left = createNode(15);
  root->left->right = createNode(19);
  root->right->left = createNode(18);
  root->right->right = createNode(21);
  
  levelOrder(root);
  return 0;
}

No comments:

If you have any doubt or suggestion let me know in comment section.

Powered by Blogger.