二叉树的前序,中序和后序遍历其实就是深度优先遍历
二叉树的层序遍历是指广度优先遍历
如果对上图的二叉树进行深度优先遍历的前序,则最终输出结果为A B D E C F G.而广度优先遍历输出结果为A B C D E F G.要想实现广度优先遍历,在这里我们可以使用队列来实现,不通过递归实现遍历。
先用二叉树结构体front记录队列的front,之后取出二叉树front,并输出,如果二叉树front的左子树不为空,就将front的左子树插入到队列中,右子树同理,之后又将front替换到新队列的front元素,再移出输出,直到队列为空就停止。
代码如下:
typedef struct BinaryTreeNode
{
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
BTDataType data;
}BTNode;
//层序遍历
void LevelOrder(BTNode* root)
{
Queue q;
QueueInit(&q);
if (root)
QueuePush(&q, root);
while (!QueueEmpty(&q))
{
//核心:上一层出的时候带下一层进
BTNode* front = QueueFront(&q);
QueuePop(&q);
printf("%c ", front->data);
if (front->left)
{
QueuePush(&q, front->left);
}
if (front->right)
{
QueuePush(&q, front->left);
}
}
printf("\n");
QueueDestory(&q);
}