Tuesday, August 14, 2012

Print each level's data in a Binary Tree in a separate line


[sourcecode]
    3
   /  \
  9   20
     /  \
    15    7

For example, the level order output of the tree above is:

3
9 20
15 7
[/sourcecode]
  1. Implemented using a "Queue".
  2. First we enter root in the queue.
  3. As root is the only node at its level, we enter a dummy node after it to signal end of level.
  4. Remove a node from queue,
  5. If it is a normal node, we enter all its children in the queue.
  6. If it is a dummy node, we enter another dummy node in the queue (this signals that we have encountered all nodes in previous level and entered their children in the queue, so this level ends here).
  7. As we need to print each level in new line, we enter a new line when we see a dummy node
[sourcecode]
void printLevel(Node* root)
{
    queue<Node*> q;
    Node *dummy = NULL;
    if(root == NULL)
        return;
    //Enter root in the queue
    else
    {
        q.push(root);
        q.push(dummy);
    }
    //If queue is empty then we are done.
    while(!q.empty())
    {
        Node* temp = q.front();
        q.pop();
        //If its a dummy node
        if(temp == NULL)
        {
            cout<<endl;
            q.push(dummy);
        }
        //Else enter node's children in the queue
        if(temp->left!=NULL)
            q.push(temp->left);
        if(temp->right!=NULL)
            q.push(temp->right);
        //Print out node's data.
        cout<<temp->data<<" ";
    }
}
[/sourcecode]

No comments:

Post a Comment