数据结构实验之二叉树八:(中序后序)求二叉树的深度
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic
Problem Description
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
Input
输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
Output
输出二叉树的深度。
Sample Input
2
dbgeafc
dgebfca
lnixu
linux
Sample Output
4
3
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
char a[100],b[101];
int d;
struct st
{
char data;
struct st *l,*r;
};
struct st*cr(int n,char a[],char b[])
{
struct st *t;
if(n==0)
return NULL;
t=(st*)malloc(sizeof(st));
t->data=b[n-1];
int p;
for(p=0;p<n;p++)
{
if(a[p]==b[n-1])
break;
}
t->l=cr(p,a,b);
t->r=cr(n-p-1,a+p+1,b+p);
return t;
};
void hou(struct st*t)
{
if(t)
{
hou(t->l);
hou(t->r);
printf("%d",t->data);
}
}
int deap(struct st*t)
{
int d=0;
if(t)
{
int l1=deap(t->l)+1;
int l2=deap(t->r)+1;
if(l1>l2)
d=l1;
else d=l2;
}
return d;
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
struct st *t;
scanf("%s %s",a,b);
int s=strlen(a);
t=cr(s,a,b);
printf("%d\n",deap(t));
}
return 0;
}
come on!