How you print level order transversal of a binary tree?


#1

How you print level order transversal of a binary tree?


#2

level order traversal of binary tree can be done with the help of queues.
in level order traversal we display or process the nodes of the same level together.

//function to display nodes in level order

void showLevel(node*p)
{ Q.push( p );
while(! Q.empty())
{ cout<value<<" ";
Q.pop();
if(p->left)
Q.push(p->left);
if(p->right)
Q.push(p->right);
if(Q.front())
p=Q.front();
else
p=NULL;
}
}


#3

For each node, first the node is visited and then it’s child nodes are put in a FIFO queue.

printLevelorder(tree)

  1. Create an empty queue q
  2. temp_node = root /start from root/
  3. Loop while temp_node is not NULL
    a) print temp_node->data.
    b) Enqueue temp_node’s children (first left then right children) to q
    c) Dequeue a node from q and assign it’s value to temp_node