二叉树的应用
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *left,*right;
}BTNode;
BTNode *CreateBTree(int a[],int n);//创建
int LeafCount(BTNode *root);//找叶子
int HeightBTree(BTNode *root);//找层数
void MirrorBTree(BTNode *root);//镜像
int main()
{
int i,j;
BTNode *root;
int a[8] = {3,2,5,8,4,7,6,9};
//二叉树的创建
root = CreateBTree(a,8);
//叶子节点的个数
i = LeafCount(root);
printf("叶子节点个数是:%d \n",i);
//返回层数
j = HeightBTree(root);
printf("二叉树的高度为:%d \n",j);
return 0;
}
//创建
BTNode *CreateBTree(int a[],int n)
{
BTNode *p,*pa,*c,*root;
int i;
root = (BTNode *)malloc(sizeof(BTNode));
root->data = a[0];
root->left = root->right = NULL;
for(i = 1;i < n;i++)
{
p = (BTNode *)malloc(sizeof(BTNode));
p->data = a[i];
p->left = p->right = NULL;
c = root;
while(c)
{
pa = c;
if(c->data > pa->data)
{
c = c->left;
}
else
{
c = c->right;
}
}
if(pa->data > p->data)
{
pa->left = p;
}
else
{
pa->right = p;
}
}
return root;
}
//找叶子
int LeafCount(BTNode *root)
{
int s1,s2,s;
if(root == NULL)
{
s = 0;
}
else
{
s1 = LeafCount(root->left);
s2 = LeafCount(root->right);
s = s1 + s2 +(!root->left && !root->right);
}
return s;
}
//找层数
int HeightBTree(BTNode *root)
{
int s1,s2,s = 0;
if(root)
{
s1 = HeightBTree(root->left);
s2 = HeightBTree(root->right);
/*if(s1 > s2)
{
s = s1 +1;
}
else
{
s = s2 + 1;
}*/
s = (s1 > s2) ? (s1+1):(s2 +1);
}
return s;
}
//镜像
void MirrorBTree(BTNode *root)
{
BTNode *t;
if(root)
{
MirrorBTree(root->left);
MirrorBTree(root->right);
t = root->left;
root->left = root->right;
root->right = t;
/*
t = root->left;
root->left = root->right;
root->right = t;
MirrorBTree(root->left);
MirrorBTree(root->right);
*/
}