题目描述
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
输入
输入数据有多组,输入T组数据。每组数据包括两个长度小于<font face="\"Times" new="" roman,="" serif\"="" style="padding: 0px; margin: 0px;">50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
输出
输出二叉树的深度。
示例输入
2 dbgeafc dgebfca lnixu linux
示例输出
4 3
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char data;
struct node*l,*r;
};
struct node*creat(char *a,char *b,int m)
{
struct node*t;
char *p;
if(m==0)
return NULL;
t=(struct node*)malloc(sizeof(struct node));
t->data=*b;
for(p=a;p;p++)
{
if(*p==*b)
break;
}
int k=p-a;
t->r=creat(p+1,b-1,m-1-k);
t->l=creat(a,b-m+k,k);
return t;
}
int depth(struct node*t)
{ int del,der;
if(!t)return 0;
if(t)
{
del=depth(t->l);
der=depth(t->r);
if(del>der)
return del+1;
else return der+1;
}
}
int main()
{
struct node*t;
int n,m;
char a[60],b[60];
scanf("%d",&n);
while(n--)
{
scanf("%s",a);
scanf("%s",b);
m=strlen(a);
t=creat(a,&b[m-1],m);
int x=depth(t);
printf("%d\n",x);
}
return 0;
}