#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct BinaryTreeNode{
int Data;
struct BinaryTreeNode *LChild,*RChild;
}BinaryTreeNode,*BinTree;
BinaryTreeNode * PreCreateBt(BinaryTreeNode *t)
{
char ch;
ch=getchar();
if(ch=='#')
t=NULL;
else
{
t=(BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));
t->Data=ch;
t->LChild=PreCreateBt(t->LChild);
t->RChild=PreCreateBt(t->RChild);
}
return t;
}
void PreOrderTransverse(BinTree t)
{
if(t==NULL)
return;
printf("%c",t->Data);
PreOrderTransverse(t->LChild);
PreOrderTransverse(t->RChild);
}
void InOrderTransverse(BinTree t)
{
if(t==NULL)
return;
InOrderTransverse(t->LChild);
printf("%c",t->Data);
InOrderTransverse(t->RChild);
}
void PostOrderTransverse(BinTree t)
{
if(t==NULL)
return;
PostOrderTransverse(t->LChild);
PostOrderTransverse(t->RChild);
printf("%c",t->Data);
}
void exchange(BinaryTreeNode *t){
BinaryTreeNode *temp = NULL;
if(t->LChild == NULL && t->RChild == NULL)
return;
else{
temp = t->LChild;
t->LChild = t->RChild;
t->RChild = temp;
}
if(t->LChild)
exchange(t->LChild);
if(t->RChild)
exchange(t->RChild);
}
void inPreOrderTransverse(BinTree t)
{
if(t==NULL)
return;
printf("%c",t->Data);
inPreOrderTransverse(t->LChild);
inPreOrderTransverse(t->RChild);
}
void inInOrderTransverse(BinTree t)
{
if(t==NULL)
return;
inInOrderTransverse(t->LChild);
printf("%c",t->Data);
inInOrderTransverse(t->RChild);
}
void inPostOrderTransverse(BinTree t)
{
if(t==NULL)
return;
inPostOrderTransverse(t->LChild);
inPostOrderTransverse(t->RChild);
printf("%c",t->Data);
}
int Size(BinaryTreeNode *t)
{
if(!t) return 0;
return Size(t->LChild)+Size(t->RChild)+1;}
int leafnum(BinaryTreeNode *t)
{
if(NULL==t) return 0;
if((NULL==t->LChild)&&(NULL==t->RChild)){
return 1;
}
return leafnum(t->LChild) + leafnum(t->RChild);
}
int Height(BinaryTreeNode *t){
int d1 = 0;
int d2 = 0;
if(NULL!=t){
d1 = Height(t->LChild) +1;
d2 = Height(t->RChild) +1;
}
return d1>=d2? d1:d2;
}
void main()
{
printf("先序建树:");
BinTree t;
t=PreCreateBt(t);
printf("\n先序遍历:");
PreOrderTransverse(t);
printf("\n中序遍历:");
InOrderTransverse(t);
printf("\n后序遍历:");
PostOrderTransverse(t);
exchange(t);
printf("\n交换后先序遍历:");
inPreOrderTransverse(t);
printf("\n交换后中序遍历:");
inInOrderTransverse(t);
printf("\n交换后后序遍历:");
inPostOrderTransverse(t);
printf("\n结点数:");
printf(" %5d \n",Size(t));
printf("\n叶子结点数");
printf("%5d \n",leafnum(t));
printf("\n高度:");
printf(" %5d \n",Height(t));
}