#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild;
struct BiTNode *rchild;
} BiTNode,*BiTree;
int Search(char pre[],char ch)
{
int a = strlen(pre);
int i;
for(i = 0; i <= a - 1; i++)
{
if(pre[i] == ch)
return i;
}
return -1;
}
BiTree Create(char pre[],char ino[],int ps,int is,int n)
{
BiTree T;
if(n == 0)
T = NULL;
else
{
int k;
k = Search(ino,pre[ps]);
if(k == -1)
{
T = NULL;
}
else
{
T = (BiTNode *)malloc(sizeof(BiTNode));
if(!T) return 0;
T->data = pre[ps];
if(k == is)//左子树为空
T->lchild = NULL;
else
{
T->lchild = Create(pre,ino,ps + 1,is,k - is);
}
if(n == k - is + 1)
{
T->rchild =NULL;
}
else
{
T->rchild = Create(pre,ino,ps + 1 + k - is,k + 1,n - 1 - (k - is));
}
}
}
return T;
}
int Depth(BiTree T)
{
int depth;
if(!T)
depth = 0;
else
{
int m,n;
m = Depth(T->lchild);
n = Depth(T->rchild);
depth = (m > n ? m : n) + 1;
}
return depth;
}
int main()
{
int n;
BiTree T;
while(~scanf("%d",&n))
{
char pre[100],ino[100];
scanf("%s",pre);
scanf("%s",ino);
T = NULL;
T = Create(pre,ino,0,0,n);
int x;
x = Depth(T);
printf("%d\n",x);
}
return 0;
}
由先序和中序还原二叉树
最新推荐文章于 2021-12-11 23:20:40 发布