#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 1000 typedef struct node{ char d; struct node *lchild,*rchild; }Tnode; void MK(char in[],int is,int ie,char pre[],int pres,int pree,Tnode **r){ int i; if(is>ie||pres>pree){ *r=NULL; }else{ *r=(Tnode*)malloc(sizeof(Tnode)); (*r)->d=pre[pres];//前序的第一个节点把中序分为左右子树 for(i=is;i<=ie;i++){ if(in[i]==pre[pres]){ MK(in,is,i-1,pre,pres+1,pres+i-is,&(*r)->lchild); MK(in,i+1,ie,pre,pres+i-is+1,pree,&(*r)->rchild); break; } } } } void porder(Tnode *r){ if(r){ porder(r->lchild); porder(r->rchild); printf("%c",r->d); } } int leaf(Tnode *r){ if(r==NULL){ return 0; }else{ if(!r->lchild&&!r->rchild){ return 1; }else return leaf(r->lchild)+leaf(r->rchild); } } int high(Tnode *r){ int h1,h2; if(r==NULL){ return 0; }else{ h1=high(r->lchild); h2=high(r->rchild); return 1+(h1>h2?h1:h2); } } void main(){ Tnode *r = NULL; char in[MAX],pre[MAX]; printf("请输入前序序列:"); gets(pre); printf("请输入中序序列:"); gets(in); MK(in,0,strlen(in)-1,pre,0,strlen(pre)-1,&r); porder(r); printf("叶子节点的个数为:%d ",leaf(r)); printf("二叉树的高度为::%d ",high(r)); }