One serious problem with your existing code is a crash when it is called on an empty tree ( root = NULL ).
You need to decide whether you want to have NULL pointers in the queue or not.
If this is not the case, you can only insert NULL values.
void traverse(Node* root) { queue<Node*> q; // no tree no level order. if(root == NULL) { return; } // push the root to start with as we know it is not NULL. q.push(root); // loop till there are nodes in the queue. while(!q.empty()) { // dequeue the front node. Node *tmpNode = q.front(); q.pop(); // print it..we are sure it is not NULL. cout<<tmpNode->value<<" "; // enqueue left child if it exists. if(tmpNode->left) { q.push(tmpNode->left); } // enqueue right child if it exists. if(tmpNode->right) { q.push(tmpNode->right); } } }
Alternatively, if you decide to have NULL in the queue, you can do:
void traverse(Node* root) { queue<Node*> q; // push the root..even if it is NULL. q.push(root); // loop till the queue is not empty. while(!q.empty()) { // dequeue the front node. Node *tmpNode = q.front(); q.pop(); // the dequeued pointer can be NULL or can point to a node. // process the node only if it is not NULL. if(tmpNode) { cout<<tmpNode->value<<" "; q.push(tmpNode->left); q.push(tmpNode->right); } } }
The first method is preferable, since a large tree has a large number of NULL child elements (leaf child nodes), and it makes no sense that they are queued in the queue when we simply do not process them later.
codaddict
source share