C代码:
#include <stdio.h>
#include <malloc.h>
typedef struct BTNode{
char data;
struct BTNode *pLchild;//p是指针,l是左,child是孩子
struct BTNode *pRchild;
}BTNode ,*PBTNode;
PBTNode CreateBTree();//二叉树的金泰创建
void PreTraverseBTree(PBTNode);//先序输出
void InTraverseBTree(PBTNode);//中序输出
void PostTraverseBTree(PBTNode); //后序输出
int getmin(PBTNode node);//求树的最小值,递归求法
int geth(PBTNode node);//求树的深度,递归求法
int getmax(PBTNode node);//求树的最大值,递归求法
int main(void){
PBTNode pT=CreateBTree();
PreTraverseBTree(pT);
printf("\n");
InTraverseBTree(pT);
printf("\n");
PostTraverseBTree(pT);
printf("\n");
int height=geth(pT);
printf("深度=%d\n",height);
int max=getmax(pT);
printf("最大值=%d\n",max);
int min=getmin(pT);
printf("最小值=%d\n",min);
return 0;
}
PBTNode CreateBTree(){
PBTNode pA=(PBTNode)malloc(sizeof(BTNode));
PBTNode pB=(PBTNode)malloc(sizeof(BTNode));
PBTNode pC=(PBTNode)malloc(sizeof(BTNode));
PBTNode pD=(PBTNode)malloc(sizeof(BTNode));
PBTNode pE=(PBTNode)malloc(sizeof(BTNode));
pA->data='A';
pB->data='B';
pC->data='C';
pD->data='D';
pE->data='E';
pA->pLchild=pB;
pA->pRchild=pC;
pB->pLchild=pB->pRchild=NULL;
pC->pLchild=pD;
pC->pRchild=NULL;
pD->pLchild=NULL;
pD->pRchild=pE;
pE->pLchild=pE->pRchild=NULL;
return pA;
}
void PreTraverseBTree(PBTNode pT){
//先访问根
//在先序访问左子树
//再先序访问右子树
if(pT!=NULL){
printf("%c\n",pT->data);
//pT->pLchild可以代表整个左子树
if(NULL!=pT->pLchild)
PreTraverseBTree(pT->pLchild);
if(NULL!=pT->pRchild)
PreTraverseBTree(pT->pRchild);
}else
return;
}
void InTraverseBTree(PBTNode pT){
//先中序访问左子树
//再访问根
//最后中序访问右子树
if(pT!=NULL){
//pT->pLchild可以代表整个左子树
if(NULL!=pT->pLchild)
InTraverseBTree(pT->pLchild);
printf("%c\n",pT->data);
if(NULL!=pT->pRchild)
InTraverseBTree(pT->pRchild);
}else
return;
}
void PostTraverseBTree(PBTNode pT){
//先后序访问左子树
//再后序访问右子树
//最后访问根
if(pT!=NULL){
//pT->pLchild可以代表整个左子树
if(NULL!=pT->pLchild)
PostTraverseBTree(pT->pLchild);
if(NULL!=pT->pRchild)
PostTraverseBTree(pT->pRchild);
printf("%c\n",pT->data);
}else
return;
}
int getmin(PBTNode node){
if(NULL==node){///递归出口
return 10000;
}else{
int m1=getmin(node->pLchild);
int m2=getmin(node->pRchild);
int m3=node->data;
int min=m1;
if(m2<min)
min=m2;
if(m3<min)
min=m3;
return min;
}
}
int getmax(PBTNode node){
if(NULL==node){///递归出口
return -1;
}else{
int m1=getmax(node->pLchild);
int m2=getmax(node->pRchild);
int m3=node->data;
int max=m1;
if(m2>max)
max=m2;
if(m3>max)
max=m3;
return max;
}
}
int geth(PBTNode node){//用递归分而治之,求左边的深度再求右边的深度不断递归
if(node==NULL) //递归出口
return 0;
else{
int left_h=geth(node->pLchild);
int right_h=geth(node->pRchild);
int max=left_h;
if(right_h>max)
max=right_h;
return max+1;
}
}
C++代码:
将上面C代码转化为C++代码