题目描述
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
输入
输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
输出
输出二叉树的深度。
示例输入
2
dbgeafc
dgebfca
lnixu
linux
示例输出
4
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
输入
输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
输出
输出二叉树的深度。
示例输入
2
dbgeafc
dgebfca
lnixu
linux
示例输出
4
3
#include<stdio.h>
#include<malloc.h>
#include<string.h>
char zx[51],hx[51];
int vis[51],maxn;
struct node
{
int data;
struct node *left,*right;
};
typedef node *tree;
tree build(int s,int e)
{
if(s>e) return NULL;
int i,ans=0,pos=0;
for(i=s;i<=e;i++)
{
if(vis[zx[i]-'a']>ans)
{
ans=vis[zx[i]-'a'];
pos=i;
}
}
tree root=(tree)malloc(sizeof(node));
root->data=zx[pos];
root->left=build(s,pos-1);
root->right=build(pos+1,e);
return root;
}
void bl(tree root,int f)
{
if(root==NULL) return;
if(maxn<f)
maxn=f;
bl(root->left,f+1);
bl(root->right,f+1);
}
void del(tree root)
{
if(root->left) del(root->left);
if(root->right) del(root->right);
free(root);
}
int main()
{
freopen("b.txt","r",stdin);
int n;
while(scanf("%d",&n)==1)
{
while(n--)
{
memset(vis,0,sizeof(vis));
scanf("%s",zx);
scanf("%s",hx);
int len=strlen(zx),i;
for(i=0;i<len;i++)
vis[hx[i]-'a']=i;
tree root=build(0,len-1);
maxn=0;
bl(root,1);
del(root);
printf("%d\n",maxn);
}
}
return 0;
}