Monday, January 16, 2017

Level order traversal on binary tree

Level order traversal or BFS traversal  on binary tree:
/*
struct node
{
    int data;
    node* left;
    node* right;
}*/
#include <queue>
void LevelOrder(node * root)
{
  queue<node *>q;
  q.push(root);
   
  while (!q.empty()) {
      node * temp = q.front();
      if (temp->left)
        q.push(temp->left);
      if (temp->right)
          q.push(temp->right);
      cout<<temp->data<<" ";
      q.pop();
  }
 
}

No comments:

Post a Comment