http://blog.163.com/wenxianliang08@126/blog/static/83583263201041195026633/
#include <stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef char ElemType;
typedef struct BiTNode
{ //定义结点
ElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,BiTree;
void DLRcreat(BiTree *&T)
//先序建立二叉树 T为指向二叉树(或者某一棵子树)根结点的指针变量
{
char ch;
ch=getchar();
if(ch=='#')T=NULL;
else
{
T=(BiTNode *)malloc(sizeof(BiTNode));//也可以T=new BiTNode;
if(T==NULL)exit(1); //此语言可以省略
T->data=ch;
DLRcreat(T->lchild);
DLRcreat(T->rchild);
}
}
//先序遍历输出二叉树所有结点
void DLRorder(BiTree *T)
{
if(T != NULL)
{
printf("%c ",T->data); // 访问根结点
DLRorder(T->lchild); // 前序遍历左子树
DLRorder(T->rchild); // 前序遍历右子树
}
}
//先序遍历输出二叉树的叶子结点
void DLRLeaf(BiTree *T)
{
if(T!=NULL)
{
if(!(T->lchild)&&!(T->rchild))
//如果一个结点的左右指针域都为空,则此结点为叶子结点
printf("%c ",T->data);
DLRLeaf(T->lchild);
DLRLeaf(T->rchild);
}
}
int Leaf(BiTree *T)
{
int LeafCount; //计算叶子结点的数目
if(T==NULL)
LeafCount=0; //空树
else
if(T->lchild==NULL&&T->rchild==NULL)
LeafCount=1; //只有一个结点的树
else
LeafCount=Leaf(T->lchild)+Leaf(T->rchild);
//整棵大树的叶子结点数目为 左右子树的叶子数目之和
return LeafCount;
}
//交换左右子树
void exchang(BiTree *&T)
{
if(T!= NULL)
{
if(T->lchild!=NULL&&T->rchild!=NULL) //当有左右孩子时才交换
{
char t;
t=T->lchild->data;
T->lchild->data=T->rchild->data;
T->rchild->data=t; //交换数据
}
exchang(T->lchild); // 递归调用
exchang(T->rchild);
}
}
//后序遍历求二叉树高度
int TreeDepth(BiTree *T)
{
int HL,HR,Max; //左右子树的高度,以及最大高度
if(T==NULL)
return 0;
else
{
HL=TreeDepth(T->lchild); //求左子树的高度
HR=TreeDepth(T->rchild); //求右子树的高度
Max=1+(HL>HR?HL:HR); //得到左右子树的高度较大者
return Max; //返回二叉树的高度
}
}
void main()
{
BiTree *T;
printf("下面先序遍历建立二叉树:\n");
DLRcreat(T);
printf("下面输出先序遍历的二叉树结点:\n");
DLRorder(T);
printf("\n");
printf("下面输出先序遍历的二叉树的叶子结点\n");
DLRLeaf(T);
printf("\n");
printf("下面输出结点交换之后的二叉树\n");
exchang(T);
DLRorder(T);
printf("\n");
printf("这棵二叉树的叶子结点数目:\n");
int LeafCount;//二叉树的结点数目
LeafCount=Leaf(T);
printf("%d\n",LeafCount);
printf("这棵二叉树的高度:\n");
int high; //二叉树的高度
high=TreeDepth(T);
printf("%d\n",high);
}