#include <iostream>
using namespace std;
#include <malloc.h>
#include <stdio.h>
#define TURE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define IINFEASIBLE -1
#define OVERFLOW -2
#define MAX_TREE_SIZE 100//二叉树的最大结点数
typedef char ElemType;
typedef int Status;
typedef struct BiTNode{
ElemType data;
struct BiTNode *lchild,*rchild;//左右孩子指针
}BiTNode,*BiTree;//结点类型,指针类型
int count=0;//CountLeaf函数用到的全局变量
Status CreateBiTree(BiTree &T)//按照先序序列建立二叉树的二叉链表
{//按先序次序输入二叉树中结点的值(一个字符),#表示空树
//构造二叉链表表示的二叉树T
char ch;
scanf("%c",&ch);
if(ch=='#')
T = NULL;//(出口)
else
{
if(!(T = (BiTNode *)malloc(sizeof(BiTNode))))//要一个二叉树结点
exit(OVERFLOW);
T -> data = ch;//生成根结点
CreateBiTree(T->lchild);//构造左子树
CreateBiTree(T->rchild);//构造右子树
}
return OK;
}
Status InorderTraverse(BiTree T)//采用二叉链表存储结构,中序遍历二叉树
{
if(T==NULL)
{
return ERROR;
}
else
{
InorderTraverse(T->lchild);//遍历左子树
printf("%c",T->data);
InorderTraverse(T->rchild);//遍历右子树
}
return OK;
}
int Depth(BiTree T)//求二叉树深度
{
int depthval,depthleft,depthright;
if(!T)
depthval = 0;
else
{
depthleft = Depth(T->lchild);//求左子树深度
depthright = Depth(T->rchild);//求右子树深度
depthval = 1 + (depthleft > depthright ? depthleft : depthright);
}
return depthval;
}
int CountLeaf(BiTree T)//需要在函数之前定义全局变量count
{
if(T)
{
if((!T->lchild)&&(!T->rchild))
{
count++;
}
else
{
CountLeaf(T->lchild);
CountLeaf(T->rchild);
}
}
return count;
}
/*void CountLeaf(BiTree T,int &count)
{
if(T)
{
if((!T->lchild)&&(!T->rchild))
count++;
CountLeaf(T->lchild,count);
CountLeaf(T->rchild,count);
}
}*/
int main()
{
BiTree T ;
cout << "请按照先序方式输入二叉树的结点元素;" << endl;
CreateBiTree(T);
cout << "创建成功的二叉树中序序列为;" <<endl;
InorderTraverse(T);
cout << endl<<"此二叉树的深度为:" <<Depth(T)<<endl;
cout << "此二叉树的叶子结点个数为:" <<CountLeaf(T)<<endl;
/*cout<<count<<endl;*/
return 0;
}