Print Level Order Traversal of a tree

Level Order Traversal of this tree would be
levelordertraversal

1 2 3 4 5 6

Approach:
Starting from the root, first the node is visited and printed then it’s child nodes are put in a queue.

struct node
{
    int value;
    struct node* left;
    struct node* right;
};
void levelOrderTraversal(struct node *root)
{
  struct node *queue[100] = {(struct node *)0};
  int size = 0;
  int queue_pointer = 0;
  struct node *temp = root;
  while(temp)
  {
      printf("%d", temp->value);
      if(temp->left)
      {
        queue[size++] = temp->left;
      }

      if(temp->right)
      {
        queue[size++] = temp->right;
      }      
      temp = queue[queue_pointer++];    
  }
}

Time Complexity:
As we are visiting each node once.So the time complexity would be O(n) where n is the number of nodes in the tree.

One Thought on “Print Level Order Traversal of a tree

  1. Pingback: Recursive Level Order Traversal of a tree | CrazyForCode

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation