二叉树的层序遍历,与其他三种遍历不同,是从二叉树的第一层开始,从左向右遍历,第一层完成
之后第二层,以此类推,直到最后一层:
上图的层序遍历的结果为:1,2,3,3,5,6
二叉树的层序遍历需要用到队列,因为层序遍历是要一层一层遍历的,所以先让一层入队列,出一
个元素时,让此节点对应的左子树先入队,再让此节点的右子树入队,依次进行遍历,出的元素进
行打印,最终打印出来的就是层序遍历,如下图:
每个序号表示一次循环
代码如下:
void LevelOrder(BTNode* root)
{
Queue q;
QueueInit(&q);
if (root)
{
QueuePush(&q, root);
}
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
printf("%d ", front->data);
if (front->lchild)
{
QueuePush(&q, front->lchild);
}
if (front->rchild)
{
QueuePush(&q, front->rchild);
}
}
QueueDestory(&q);
}
判断是否为完全二叉树:
其实思想和层序遍历的思想很像,就是一层一层遍历下去,当遇到空指针的时候,就要出循环,
跳出后再进行遍历,看后面还有没有不为空的指针,如果有,就不是完全二叉树,没有的话,就是
完全二叉树。
代码如下:
1.层序遍历二叉树(这里与上面的有些不同,会存在空指针):
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
if (front == NULL)
{
break;
}
else
{
QueuePush(&q, front->lchild);
QueuePush(&q, front->rchild);
}
}
2.判断是否为完全二叉树:
//判断
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
if (front)
{
QueueDestory(&q);
return false;
}
}
QueueDestory(&q);
return true;
整体代码:
//判断是否为完全二叉树
bool BinaryTreeComplete(BTNode* root)
{
Queue q;
QueueInit(&q);
if (root)
{
QueuePush(&q, root);
}
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
if (front == NULL)
{
break;
}
else
{
QueuePush(&q, front->lchild);
QueuePush(&q, front->rchild);
}
}
//判断
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
if (front)
{
QueueDestory(&q);
return false;
}
}
QueueDestory(&q);
return true;
}