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;
}
首先将head
节点插入队列。当队列不为空时,循环将进行迭代。从头节点开始,在每次迭代中删除一个节点并将非空子节点插入队列中。在每次迭代中,一个节点退出,其非空子节点被推送。在下一次迭代中,下一个最旧的发现顶点,现在位于队列的前面,被取出(按照它们被发现的顺序),然后处理它们以检查它们的子节点。
A
/ \
/ \
B C
/ \ \
/ \ \
D E F
/ \ / \
/ \ / \
G H I J
iteration Vertex Selection Discovery Queue State
initial : A
1 A : B C {A is removed and its children inserted}
2 B : C D E {B is removed and its only child inserted}
3 C : D E F {C is removed and its children inserted}
4 D : E F G H {D is removed and its children inserted}
5 E : F G H {E is removed and has not children}
6 F : G H I J {F is removed and its children inserted}
7 G : H I J {G is removed has no children}
8 H : I J {H is removed has no children}
9 I : J {I is removed has no children}
10 J : (empty) {J is removed has no children}
当我们得到队列中没有更多等待选择的已发现顶点时,迭代停止,因此选择了在二叉树(图连接组件)中发现的所有顶点。
我的代码首先传递队列中的节点,然后再次递归遍历这些子节点,从而创建 DFS 模式。如果必须进行递归,则需要检查队列是否为空作为基本条件。还要检查一下您是如何通过队列的,我认为这可能是不正确的。我会建议一个迭代解决方案。