目录
一、前序遍历
遍历顺序:根节点->左子树->右子树
代码实现
void PrevOrder(BTNode* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
printf("%d ", root->data);
PrevOrder(root->left);
PrevOrder(root->right);
}
二、中序遍历
中序遍历:左子树->根节点->右子树
代码实现
void InOrder(BTNode* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
InOrder(root->left);
printf("%d ", root->data);
InOrder(root->right);
}
三、后序遍历
后序遍历:左子树->右子树->根节点
代码实现
void PostOrder(BTNode* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
PostOrder(root->left);
PostOrder(root->right);
printf("%d ", root->data);
}
四、层序遍历
一层一层的打印数据。
需要借助队列实现。先push根节点,若队列不为空,则删除队头,并push对头数据的left和right,直到队列为NULL。(需将队列push的数据类型进行更改,改为根节点的类型)
代码实现
void LevelOrder(BTNode* root)
{
Queue q;
QueueInit(&q);
if (root)
QueuePush(&q, root);//将根节点的指针进入队列
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
printf("%d ", front->data);
QueuePop(&q);
if (front->left)
QueuePush(&q, front->left);
if (front->right)
QueuePush(&q, front->right);
}
printf("\n");
QueueDestroy(&q);
}
判断是否为完全二叉树
使用层序的方式判断,将NULL节点也传入队列,出到第一个NULL时,判断到队列为NULL时,中间是否有不为空的数据,若有则返回false。
bool TreeComplete(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->left);
QueuePush(&q, front->right);
}
}
//判断之后是否出现不为空的数据
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
if (front != NULL)
{
QueueDestroy(&q);//记得销毁,否则出现内存泄漏
return false;
}
}
QueueDestroy(&q);
return true;
}