Printing a Binary Tree in Level Order

Given a binary tree, print out the tree in level order (ie, from left to right, level by level). Output a newline after the end of each level.

C++:
01 void PrintLevel(Node* head)
02 {
03     queue <Node*> q1;
04     queue <Node*> q2;
05     queue <Node*>* q=&q1;
06     queue <Node*>* p=&q2;
07     if(head==NULL)
08         return;
09     q1.push(head);
10     while(!q->empty()){
11         Node* tmp=q->front();
12         q->pop();
13         cout<<tmp->value<<” “;
14         if(tmp->left)
15             p->push(tmp->left);
16         if(tmp->right)
17             p->push(tmp->right);
18         if(q->empty()){
19             cout<<endl;
20             queue <Node*>* t=q;
21             q=p;
22             p=t;
23         }
24     }
25 }
Advertisements
This entry was posted in Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s