问题描述
我正在尝试编写二进制树中广度优先搜索的代码.我已经将所有数据存储在队列中,但是我不知道如何去所有节点并消耗所有孩子.
这是我在C中的代码:
void breadthFirstSearch (btree *bt, queue **q) { if (bt != NULL) { //store the data to queue if there is if (bt->left != NULL) enqueue (q, bt->left->data); if (bt->right != NULL) enqueue (q, bt->right->data); //recursive if (bt->left != NULL) breadthFirstSearch (bt->left, q); if (bt->right != NULL) breadthFirstSearch (bt->right, q); } }
我已经列出了根数据,但是它仍然无法正常工作. 谁能指出我的错误?
推荐答案
可以在没有递归的情况下轻松编写BFS.只需使用队列订购您的扩展:
void BFS(btree *start) { std::deque<btree *> q; q.push_back(start); while (q.size() != 0) { btree *next = q.front(); // you may want to print the current node here or do other processing q.pop_front(); if (next->left) q.push_back(next->left); if (next->right) q.push_back(next->right); } }
关键是您不需要递归地穿越树;您只需让数据结构处理访问节点的顺序即可.
请注意,我在这里使用C ++ Deque,但是任何使您可以将物品放在背面并从前面获取的任何东西都可以正常工作.
其他推荐答案
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}
当我们知道没有更多发现的顶点等待在队列中选择的顶点,因此在队列中,因此选择了所有在二进制树(Graph connected Component)中发现的顶点.
i您的代码首先您通过队列中的节点加入,然后再次递归地穿越这些孩子,从而创建DFS模式.如果您必须进行递归,则需要检查队列是否为基本条件为空.还要检查您如何通过队列,我认为这可能是不正确的.我建议迭代解决方案.
其他推荐答案
您在这里没有进行广度的首先遍历.取而代之的是,您正在将队列内的左右元素重入并移至左侧子树.您首先要用尽左子树,然后移至右侧子树.
编写一个程序以加入节点.
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 }