void bfs_bintree (btree_t *head) { queue_t *q; btree_t *temp; q = queue_allocate (); queue_insert (q, head); while (!queue_is_empty (q)) { temp = queue_remove (q); if (temp->left) queue_insert (temp->left); if (temp->right) queue_insert (temp->right); } queue_free (q); return; }
First, the head node is inserted into the queue. The loop will repeat until the queue is empty. Starting with the head of a node, at each iteration one node is deleted and non-zero children are placed in the queue. At each iteration, a node is selected, and its non-bubble children are discarded. At the next iteration, the next old found vertex, which is now in the front of the queue, is taken out (in the order they were found), and then processed to check their child.
A / \ / \ BC / \ \ / \ \ DEF / \ / \ / \ / \ GHIJ iteration Vertex Selection Discovery Queue State initial : A 1 A : BC {A is removed and its children inserted} 2 B : CDE {B is removed and its only child inserted} 3 C : DEF {C is removed and its children inserted} 4 D : EFGH {D is removed and its children inserted} 5 E : FGH {E is removed and has not children} 6 F : GHIJ {F is removed and its children inserted} 7 G : HIJ {G is removed has no children} 8 H : IJ {H is removed has no children} 9 I : J {I is removed has no children} 10 J : (empty) {J is removed has no children}
Above the iteration, it stops when we get that there is no more open vertex in the queue waiting to be selected, therefore all vertices found in the binary tree (the component associated with the graph) are selected.
I first pass your code to the queue of the nodes in the queue, and then recursively traverse these children, which creates a DFS template. If you need to do a recursion, you need to check if there is a queue as a basic condition. Also check how you go through the queue, I think this might be wrong. I would suggest an iterative solution.
source share