SDUT OJ 数据结构实验之二叉树八:(中序后序)求二叉树的深度

时间:2021-09-11 16:49:44

数据结构实验之二叉树八:(中序后序)求二叉树的深度

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。

Input

输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。

Output

输出二叉树的深度。

Sample Input

2
dbgeafc
dgebfca
lnixu
linux

Sample Output

4
3
#include <stdio.h>
#include <stdlib.h>
#include <string.h> struct node
{
int data;
char c;
struct node *lt, *rt;
}; char s1[100],s2[100]; struct node *creat(int n, char s1[], char s2[])
{
int i=0;
struct node *root;
if(n==0) return NULL;
root=(struct node *)malloc(sizeof(struct node));
root->c=s2[n-1];
for(i=0; i<n; i++){
if(s1[i]==s2[n-1]){
root->lt=creat(i, s1, s2);
root->rt=creat(n-1-i, s1+i+1, s2+i);
}
}
return root;
} /*void fir(struct node *root)
{
if(root){
printf("%c",root->c);
fir(root->lt);
fir(root->rt);
}
}*/ int h(struct node *root)
{
if(root->lt==NULL&&root->rt==NULL){
root->data=1;
}
else if(root->lt==NULL&&root->rt!=NULL){
root->data=h(root->rt)+1;
} else if(root->lt!=NULL&&root->rt==NULL){
root->data=h(root->lt)+1;
}
else if(root->lt!=NULL&&root->rt!=NULL){
if(h(root->lt)>h(root->rt)){
root->data=h(root->lt)+1;
}
else{
root->data=h(root->rt)+1;
}
}
return root->data;
} int main()
{
int n;
scanf("%d",&n);
while(n--){
scanf("%s %s",s1,s2);
int len = strlen(s1);
struct node *root;
root=creat(len,s1,s2);
//fir(root);
printf("%d\n",h(root)); }
return 0;
}