I\'m trying to write the codes for breadth-first search in binary tree. I\'ve stored all the data in a queue, but I can\'t figure out how to travel to all nodes and consume all
You are not doing a breadth first traversal here. Instead you are enqueuing the left and right element inside the queue and moving to the left subtree. You are exhausting the left subtree first and then moving on to the right subtree.
Write a procedure to enqueue the node instead.
void breadthFirstSearch (btree *bt, queue **q) {
btree *tmpNode;
enqueue(q,bt); //Assuming your root node has data
while (!isempty(q)) //Assume isempty returns false when queue is not empty
{
tmpNode = dequeue(q);
//Do whatever you want to do with tmpNode->data
enqueue(tmpNode->left);
enqueue(tmpNode->right);
/* If this is a acyclic graph(tree) then this procedure should do, else you have to mark the nodes you have visited in-order not to end in a cycle */
}
}
int main()
{
breadthFirstSearch(bt,q)
return 0
}