#include <stdio.h>
#include <malloc.h>
//静态创建二叉树
typedef struct TNode{
char data;
struct TNode * pLchild;
struct TNode * pRchild;
}TNODE,*PTNODE;
PTNODE CreateTree();//创建二叉树
void PrePrintTree(PTNODE);//先序遍历
void PrePrintTreeCount(PTNODE,int *);//先序遍历以及叶子节点的个数
void InPrintTree(PTNODE);//中序遍历
void PostPrintTree(PTNODE);//后续遍历
int main(void){
PTNODE pT = CreateTree();
printf("先序遍历:");
PrePrintTree(pT);
printf("\n");
printf("中序遍历:");
InPrintTree(pT);
printf("\n");
printf("后序遍历:");
PostPrintTree(pT);
printf("\n");
//先序遍历以及计算叶子节点个数
int count = 0;
printf("先序遍历:");
PrePrintTreeCount(pT,&count);
printf("叶子个数:%d\n",count);
return 0;
}
//创建二叉树
PTNODE CreateTree(){
PTNODE pA = (PTNODE)malloc( sizeof(TNODE) );
PTNODE pB = (PTNODE)malloc( sizeof(TNODE) );
PTNODE pC = (PTNODE)malloc( sizeof(TNODE) );
PTNODE pD = (PTNODE)malloc( sizeof(TNODE) );
PTNODE pE = (PTNODE)malloc( sizeof(TNODE) );
pA->data = 'A';
pB->data = 'B';
pC->data = 'C';
pD->data = 'D';
pE->data = 'E';
pA->pLchild = pB;
pA->pRchild = pC;
pB->pLchild = NULL;
pB->pRchild = NULL;
pC->pLchild = pD;
pC->pRchild = NULL;
pD->pLchild = NULL;
pD->pRchild = pE;
pE->pLchild = NULL;
pE->pRchild = NULL;
return pA;
}
//先序遍历
void PrePrintTree(PTNODE pT){
if(pT){
printf("%c\t",pT->data);
if(pT->pLchild){
PrePrintTree(pT->pLchild);
}
if(pT->pRchild){
PrePrintTree(pT->pRchild);
}
}
}
//中序遍历
void InPrintTree(PTNODE pT){
if(pT){
if(pT->pLchild){
InPrintTree(pT->pLchild);
}
printf("%c\t",pT->data);
if(pT->pRchild){
InPrintTree(pT->pRchild);
}
}
}
//后序遍历
void PostPrintTree(PTNODE pT){
if(pT){
if(pT->pLchild){
PostPrintTree(pT->pLchild);
}
if(pT->pRchild){
PostPrintTree(pT->pRchild);
}
printf("%c\t",pT->data);
}
}
//先序遍历以及叶子节点的总计
void PrePrintTreeCount(PTNODE pT,int * count){
if(pT){
printf("%c\t",pT->data);
if(!pT->pLchild && !pT->pRchild){//左右子节点都为空的时候
(*count)++;
}
if(pT->pLchild){
PrePrintTreeCount(pT->pLchild,count);
}
if(pT->pRchild){
PrePrintTreeCount(pT->pRchild,count);
}
}
}