Consider the below program, and identify what the function is doing.
void function(Node* root)
{ if (root == NULL)
return ;
queue<Node*> q;
q.push(root);
while (q.empty() == false ) {
Node* node = q.front();
cout << node->data << " " ;
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
}
} |
(A)
In order traversal of a tree
(B)
Normal traversal of a tree
(C)
Level order traversal of a tree
(D)
None
Answer: (C)
Explanation:
The above code is the level order traversal of the tree using Queue. We need to visit the nodes in a lower level before any node in a higher level, this idea is quite similar to that of a queue. Push the nodes of a lower level in the queue. When any node is visited, pop that node from the queue and push the child of that node in the queue.
This ensures that the node of a lower level is visited prior to any node of a higher level.
Hence Option (C) is the correct answer.
Quiz of this Question
Please comment below if you find anything wrong in the above post