目录
1、通过前序遍历的数组"ABD##E#H##CF##G##"构建二叉树:
2、二叉树销毁void BinaryTreeDestory(BTNode** root);
bool BinaryTreeComplete(BTNode* root);
一、二叉树补充——层序遍历:
0、层序遍历
层序遍历:除了先序遍历、中序遍历、后序遍历外,还可以对二叉树进行层序遍历。设二叉树的根节点所在 层数为1,层序遍历就是从所在二叉树的根节点出发,首先访问第一层的树根节点,然后从左到右访问第2层 上的节点,接着是第三层的节点,以此类推,自上而下,自左至右逐层访问树的结点的过程就是层序遍历。
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);
}
1、通过前序遍历的数组"ABD##E#H##CF##G##"构建二叉树:
#include <stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef char BTDataType;
typedef struct BinaryTreeNode
{
BTDataType data;
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
}BTNode;
BTNode* BuyNode(BTDataType x)
{
BTNode* node = (BTNode*)malloc(sizeof(BTNode));
assert(node);
node->data = x;
node->left = NULL;
node->right = NULL;
return node;
}
void InOrder(BTNode* root)
{
if (root == NULL)
{
return;
}
InOrder(root->left);
printf("%c ", root->data);
InOrder(root->right);
}
BTNode* CreateTree(char* str ,int*pi)
{
if(str[*pi] == '#')
{
(*pi)++;
return NULL;
}
BTNode* root = BuyNode(str[(*pi)++]);
root->left = CreateTree(str,pi);
root->right= CreateTree(str,pi);
return root;
}
int main()
{
char str[100];
scanf("%s",str);
int i = 0;
BTNode* root = CreateTree(str,&i);
InOrder(root);
return 0;
}
2、二叉树销毁
void BinaryTreeDestory(BTNode** root);
// 二叉树销毁
void BinaryTreeDestory(BTNode* root)
{
if (root == NULL)
{
return;
}
BinaryTreeDestory(root->left);
BinaryTreeDestory(root->right);
free(root);
}
3、判断二叉树是否是完全二叉树
bool BinaryTreeComplete(BTNode* root);
bool BinaryTreeComplete(BTNode* root)
{
Queue q;
QueueInit(&q);
if (root)
{
QueuePush(&q, root);
}
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
if (front)
{
QueuePush(&q, front->left);
QueuePush(&q, front->right);
}
else
{
//遇到空以后,跳出层序遍历
break;
}
}
//如果后面全是空则是完全二叉树
//如果后面还有非空,则不是完全二叉树
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
if (front)
{
QueueDestroy(&q);
return false;
}
}
QueueDestroy(&q);
return true;
}