[sourcecode] 3 / \ 9 20 / \ 15 7 For example, the level order output of the tree above is: 3 9 20 15 7 [/sourcecode]
- Implemented using a "Queue".
- First we enter root in the queue.
- As root is the only node at its level, we enter a dummy node after it to signal end of level.
- Remove a node from queue,
- If it is a normal node, we enter all its children in the queue.
- 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).
- 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