#include<stdio.h>
#include<malloc.h>
#include<math.h>
#define tlen 100
typedef struct BiTnode
{
int data;
struct BiTnode *lchild,*rchild;
}BiTnode,*BiTree;
/*******************************树相关操作*******************************************/
BiTree CreateTree(BiTree Bt)
{
char ch;
ch=getchar();
if(ch=='#')
Bt=NULL;
else
{
if(!(Bt=(BiTnode *)malloc (sizeof (BiTnode))))
printf("创建节点失败!\n");
Bt->data=ch;
Bt->lchild=CreateTree(Bt->lchild);//递归创建左子树
Bt->rchild=CreateTree(Bt->rchild);//创建右子树
}
return Bt;
}
/*
求解二叉树中节点的个数:
思路:
(1)如果二叉树为空,节点个数为0
(2)如果二叉树不为空,二叉树节点个数 = 左子树节点个数 + 右子树节点个数 + 1
*/
int Get_Num_Of_Tree(BiTree T)
{
if(T==NULL)
return 0;//递归出口
else
return Get_Num_Of_Tree(T->lchild)+Get_Num_Of_Tree(T->rchild)+1;
}
/*
求二叉树的深度:
递归解法:
(1)如果二叉树为空,二叉树的深度为0
(2)如果二叉树不为空,二叉树的深度 = max(左子树深度, 右子树深度) + 1
*/
int Get_Depth_Of_Tree(BiTree T)
{
if(T==NULL)//递归出口
return 0;
int depleft=Get_Depth_Of_Tree(T->lchild);
int depright=Get_Depth_Of_Tree(T->rchild);
return depleft>depright ? (depleft+1):(depright+1);
}
/*前序遍历*/
void Pre_Travel(BiTree T)
{
if(T==NULL)
return;
printf("%c",T->data);//输出根节点
Pre_Travel(T->lchild);
Pre_Travel(T->rchild);
}
/*中序遍历*/
void Mid_Travel(BiTree T)
{
if(T==NULL)
return;
Pre_Travel(T->lchild);
printf("%c",T->data);//输出根节点
Pre_Travel(T->rchild);
}
/*后序遍历*/
void Back_Travel(BiTree T)
{
if(T==NULL)
return;
Back_Travel(T->lchild);
Back_Travel(T->rchild)
printf("%c",T->data);//输出根节点
}
void Level_Travel(BiTree T)
{
}
//获取树的叶子节点数
/*
(1)如果为NULL则为返回0
(2)如果只有一个根节点,则返回1
(3)如果二叉树不为空,且左右子树不同时为空,
返回左子树中叶子节点个数加上右子树中叶子节点个数
*/
int Get_Num_Of_leaf(BiTree T)
{
if(T==NULL)
return 0;
if(T->lchild==NULL&&T->rchild==NULL)
return 1;
int numleft=Get_Num_Of_leaf(T->lchild);
int numright=Get_Num_Of_leaf(T->rchild);
return numleft+numright;
}
/*
判断二叉树是不是平衡树
*/
int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
/*
(1)如果为空,返回真
(2)如果左右子树高度之差不大于1,返回真,否则为假。
*/
bool ISAVL(BiTree T, int height)
{
if(T==NULL)
{
height=NULL;
return true;
}
int heightleft;
bool resultleft=ISAVL(T->lchild,heightleft);
int heightright;
bool resultright=ISAVL(T->rchild,heightright);
if(resultleft&&resultright&&abs(heightleft-resultright)<=1)
//左右子树高度之差不能大于1
{
height=max(heightleft,heightright)+1;
return true;
}
else
{
height=max(heightleft,heightright)+1;
return false;
}
}
void main()
{
BiTree T;
T=CreateTree(T);
printf("二叉树节点数目:%d\n",Get_Num_Of_Tree(T));
printf("二叉树深度:%d\n",Get_Depth_Of_Tree(T));
printf("前序遍历结果:");
Pre_Travel(T);
printf("\n中序遍历结果:");
Mid_Travel(T);
printf("\n后序遍历结果:");
Back_Travel(T);
printf("\n叶子节点数为:");
printf("%d\n",Get_Num_Of_leaf(T));
int height=0;
if(ISAVL(T,height))
{
printf("此二叉树为平衡二叉树\n");
}else
{
printf("此二叉树不为平衡二叉树\n");
}
}
附图: