#include<stdio.h>
#include<stdlib.h>
#define MAX 50
typedef char ElemType;
typedef struct node *Bintree;
struct node
{
ElemType data;
Bintree lchild;
Bintree rchild;
};
Bintree Recover(ElemType Pre[],ElemType In[],int len)
{
Bintree T;
int i;
if(!len)
return NULL;
else
{
T=malloc(sizeof(struct node));
T->data=Pre[0];
for(i=0;i<len;i++)//在中序遍历序列中找根节点
{
if(Pre[0]==In[i])
break;
}
//递归构建左右子树
T->lchild=Recover(Pre+1,In,i);
T->rchild=Recover(Pre+1+i,In+i+1,len-i-1);
}
return T;
}
int GetHigh(Bintree T)
{
int HL,HR,Height;
if(!T)
return 0;
else
{
HL=GetHigh(T->lchild);
HR=GetHigh(T->rchild);
Height=HL>HR?HL:HR;
Height++;//树高为左右树高较大者加1
}
return Height;
}
int main()
{
Bintree Tree;
ElemType Preorder[MAX+1],Inorder[MAX+1];
int N,H;
scanf("%d",&N);
scanf("%s",Preorder);
scanf("%s",Inorder);
Tree=Recover(Preorder,Inorder,N);
H=GetHigh(Tree);
printf("%d\n",H);
return 0;
}
5-23 还原二叉树
最新推荐文章于 2021-05-19 16:17:34 发布