// 通过前序遍历的数组"ABD##E#H##CF##G##"构建二叉树
BTNode* BinaryTreeCreate(BTDataType* a, int n, int* pi);
if (a[*pi] == '#' || (*pi) >= n)
{
(*pi)++;
return NULL;
}
BTNode* root = (BTNode*)malloc(sizeof(BTNode));
root->_data = a[*pi];
(*pi)++;
root->_left = BinaryTreeCreate(a, n, pi);
root->_right = BinaryTreeCreate(a, n, pi);
return root;
// 二叉树销毁
void BinaryTreeDestory(BTNode** root);
void BinaryTreeDestory(BTNode* root)
{
if (root == NULL)
return;
BinaryTreeDestory(root->_left);
BinaryTreeDestory(root->_right);
free(root);
}
// 二叉树节点个数
int BinaryTreeSize(BTNode* root);
int BinaryTreeSize(BTNode* root)
{
if (root == NULL)
return 0;
static size = 0;
size++;
BinaryTreeSize(root->_left);
BinaryTreeSize(root->_right);
return size;
}
// 二叉树第k层节点个数
int BinaryTreeLevelKSize(BTNode* root, int k);
int BinaryTreeLevelKSize(BTNode* root, int k)
{
if (root == NULL)
return 0;
if (k == 1)
return 1;
return BinaryTreeLevelKSize(root->_left, k - 1) + BinaryTreeLevelKSize(root->_right, k - 1);
}
// 二叉树查找值为x的节点
BTNode* BinaryTreeFind(BTNode* root, BTDataType x);
BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
if (root == NULL)
return NULL;
if (root->_data == x)
return root;
BTNode* left = BinaryTreeFind(root->_left, x);
if (left)
return left;
BTNode*right = BinaryTreeFind(root->_right, x);
if (right)
return right;
}
// 二叉树前序遍历
void BinaryTreePrevOrder(BTNode* root);
void BinaryTreePrevOrder(BTNode* root)
{
if (root == NULL)
return;
printf("%c ", root->_data);
BinaryTreePrevOrder(root->_left);
BinaryTreePrevOrder(root->_right);
}
// 二叉树中序遍历
void BinaryTreeInOrder(BTNode* root);
void BinaryTreeInOrder(BTNode* root)
{
BinaryTreeInOrder(root->_left);
printf("%c ", root->_data);
BinaryTreeInOrder(root->_right);
}
// 二叉树后序遍历
void BinaryTreePostOrder(BTNode* root);
void BinaryTreePostOrder(BTNode* root)
{
BinaryTreePostOrder(root->_left);
BinaryTreePostOrder(root->_right);
printf("%c ", root->_data);
}
// 层序遍历
void BinaryTreeLevelOrder(BTNode* root);
void BinaryTreeLevelOrder(BTNode* root)
{
Queue q;
QueueInit(&q);
if (root)
QueuePush(&q, root);
while (!QueueEmpty(&q))
{
BTNode* node=QueueFrontdata(&q);
printf("%c ", node->_data);
QueuePop(&q);
if (node->_left)
{
QueuePush(&q, node->_left);
}
if (node->_right)
{
QueuePush(&q, node->_right);
}
}
}
// 判断二叉树是否是完全二叉树
int BinaryTreeComplete(BTNode* root);
int BinaryTreeComplete(BTNode* root)
{
Queue q;
QueueInit(&q);
if (root)
QueuePush(&q, root);
while (!QueueEmpty(&q))
{
BTNode* tmp= QueueFrontdata(&q);
QueuePop(&q);
if (tmp == NULL)
break;
QueuePush(&q, tmp->_left);
QueuePush(&q, tmp->_right);
}
while (!QueueEmpty(&q))
{
if (QueueFrontdata(&q) != NULL)
{
QueueDestory(&q);
return false;
}
QueuePop(&q);
}
QueueDestory(&q);
return true;
}
// 二叉树叶子节点个数
int BinaryTreeLeafSize(BTNode* root);
int BinaryTreeLeafSize(BTNode* root)
{
if (root == NULL)
return 0;
if (root->_left == NULL && root->_right == NULL)
return 1;
return BinaryTreeLeafSize(root->_left)+ BinaryTreeLeafSize(root->_right);
}
结尾:今天的分享到此结束,喜欢的朋友如果感觉有帮助可以点赞三连支持,咱们共同进步!