已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
输出二叉树的深度。
2
dbgeafc
dgebfca
lnixu
linux
4
3
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char lat[55], ino[55];
typedef struct BNodeTree
{
char data;
struct BNodeTree *lc, *rc;
}BNodeTree, *Tree;
void CreateTree(Tree &root, char *ino, char *lat, int n)
{
if(n == 0)
root = NULL;
else
{
root = new BNodeTree;
root->data = lat[n-1];
int i;
for(i = 0; i < n;i ++)
{
if(ino[i] == lat[n-1])
break;
}
CreateTree(root->lc, ino, lat, i);
CreateTree(root->rc, ino+i+1, lat+i, n-i-1);
}
}
int Max(int a, int b)
{
if(a > b) return a+1;
else return b+1;
}
int Deep(Tree &root)
{
int count = 0;
if(root != NULL)
{
int len1 = Deep(root->lc);
int len2 = Deep(root->rc);
count = Max(len1, len2);
}
return count;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%s", ino);
scanf("%s", lat);
int n = strlen(ino);
Tree root;
CreateTree(root, ino, lat, n);
printf("%d\n", Deep(root));
}
return 0;
}