该代码的功能:二叉树的前序、中序、后序、二叉树的个数、二叉树的高度、二叉树的叶子节点个数、二叉树第k层的节点个数。
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int TypeData;
typedef struct BinaryTreeNode
{
TypeData data;
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
}BTNode;
BTNode* Buynode(TypeData x)
{
BTNode* node = (BTNode*)malloc(sizeof(BTNode));
if (node == NULL)
{
perror("malloc fail");
return NULL;
}
node->data = x;
node->left = NULL;
node->right = NULL;
return node;
}
BTNode* CreateBinaryTreeNode()
{
BTNode* node1 = Buynode(1);
BTNode* node2 = Buynode(2);
BTNode* node3 = Buynode(3);
BTNode* node4 = Buynode(4);
BTNode* node5 = Buynode(5);
BTNode* node6 = Buynode(6);
BTNode* node7 = Buynode(7);
node1->left = node2;
node1->right = node3;
node2->left = node4;
node2->right = node5;
node3->left = node6;
node3->right = node7;
return node1;
}
void PrevOrder(BTNode* root)//前序遍历
{
if (root == NULL)
{
printf("N ");
return;
}
printf("%d ", root->data);
PrevOrder(root->left);
PrevOrder(root->right);
}
void InOrder(BTNode* root)//中序遍历
{
if (root == NULL)
{
printf("N ");
return;
}
InOrder(root->left);
printf("%d ", root->data);
InOrder(root->right);
}
void PostOrder(BTNode* root)//后序遍历
{
if (root == NULL)
{
printf("N ");
return;
}
PostOrder(root->left);
PostOrder(root->right);
printf("%d ", root->data);
}
int BTreeSize(BTNode* root)//遍历二叉树的个数
{
return root == NULL ? 0 : BTreeSize(root->left) + BTreeSize(root->right) + 1;
}
int BTreeleafSize(BTNode* root)//求叶子节点的个数
{
if (root == NULL)
{
return 0;
}
if (root->left == NULL && root->right == NULL)
{
return 1;
}
return BTreeleafSize(root->left) + BTreeleafSize(root->right);
}
int BTreeHeight(BTNode* root)//求二叉树的高度
{
if (root == NULL)
return 0;
int leftHeight = BTreeHeight(root->left);
int rightHeight = BTreeHeight(root->right);
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
// 二叉树第k层结点个数
int BTreeLevelKSize(BTNode* root, int k)
{
if (root == NULL)
return 0;
if (k == 1)
return 1;
return BTreeleafSize(root->left, k - 1) + BTreeleafSize(root->right, k - 1);
}
int main()
{
int size = 0;
BTNode* root = CreateBinaryTreeNode();
PrevOrder(root);
printf("\n");
InOrder(root);
printf("\n");
PostOrder(root);
printf("\n");
printf("BTreeSize:%d\n", BTreeSize(root));//二叉树的个数
printf("BTreeHeight:%d\n", BTreeHeight(root));//二叉树的高度
printf("BTreeleafSize:%d\n", BTreeleafSize(root));//求叶子节点的个数
printf("BTreeLevelKSize:%d\n", BTreeLevelKSize(root,3));//第k个节点的个数
return 0;
}