对于广度优先遍历二叉树,也就是按层次的去遍历。依次遍历根节点,然后是左孩子和右孩子。在这里,我们需要根据左右孩子的顺序来输出,所以就是先进先出的原则,那么我们当然就想到了队列这个数据结构。可以在rear依次插入左右孩子,在front依次读取并删除左右孩子,这样就保证了层次的输出。
void BreathFirstSearch(BTree *root)
{
Queue<BTree *> queue = new Queue();
queue.Enqueue(root);
while(!queue.IsEmpty())
{
root = queue.Dequeue();
printf("%c",root->data);
if(root->lchild != NULL)
{
queue.Enqueue(root->lchild);
}
if(root->rchild != NULL)
{
queue.Enqueue(root->rchild);
}
}
}