// 二叉树节点个数
int BinaryTreeSize(BTNode* root)
{
return root == NULL ? 0 : BinaryTreeSize(root->_left) + BinaryTreeSize(root->_right) + 1;
}
// 二叉树叶子节点个数
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);
}
// 二叉树第k层节点个数
int BinaryTreeLevelKSize(BTNode* root, int k)
{
if (k==0||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)
{
if (root == NULL)
return NULL;
if (x == root->_data)
return root;
BTNode* findleft = BinaryTreeFind(root->_left, x);
if (findleft != NULL)
return findleft;
BTNode* findright = BinaryTreeFind(root->_right, x);
if (findright != NULL)
return findright;
return NULL;
}
// 二叉树前序遍历
void BinaryTreePrevOrder(BTNode* root)
{
if (root == NULL)
{
printf("#");
return;
}
printf("%c", root->_data);
BinaryTreePrevOrder(root->_left);
BinaryTreePrevOrder(root->_right);
}
// 二叉树中序遍历
void BinaryTreeInOrder(BTNode* root)
{
if (root == NULL)
{
printf("N");
return;
}
BinaryTreeInOrder(root->_left);
printf("%d ", root->_data);
BinaryTreeInOrder(root->_right);
}
// 二叉树后序遍历
void BinaryTreePostOrder(BTNode* root)
{
if (root == NULL)
{
printf("N");
return;
}
BinaryTreePostOrder(root->_left);
BinaryTreePostOrder(root->_right);
printf("%d ", root->_data);
}
// 层序遍历
void BinaryTreeLevelOrder(BTNode* root)
{
if (root == NULL)
return;
Queue tree;
QueueInit(&tree);
QueuePush(&tree, root);
while (!QueueEmpty(&tree))
{
BTNode* front = QueueFront(&tree);
QueuePop(&tree);
printf("%d ", front->_data);
if(front->_left)
QueuePush(&tree, front->_left);
if(front->_right)
QueuePush(&tree, front->_right);
}
QueueDestroy(&tree);
}
int BinaryTreeComplete(BTNode* root)
{
if (root == NULL)
return 1;
Queue q;
QueueInit(&q);
QueuePush(&q, root);
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
if (front == NULL)
{
while (!QueueEmpty(&q))
{
front = QueueFront(&q);
if (front != NULL)
return 0;
QueuePop(&q);
}
return 1;
}
QueuePush(&q, front->_left);
QueuePush(&q, front->_right);
}
QueueDestroy(&q);
return 1;
}
「C语言数据结构实战:二叉树的完整实现(含层序遍历与完全性判断)
最新推荐文章于 2025-12-09 19:50:25 发布
863

被折叠的 条评论
为什么被折叠?



