题目描述
现给定一棵二叉树的先序遍历序列和中序遍历序列,要求你计算该二叉树的高度。
输入格式
输入包含多组测试数据,每组输入首先给出正整数N(<=50),为树中结点总数。下面2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出
对于每组输入,输出一个整数,即该二叉树的高度。
样例输入
9
ABDFGHIEC
FDHGIBEAC
7
Abcdefg
gfedcbA
样例输出
5
7
#include <stdio.h>
#include <string.h>
char pre[60], in[60];
typedef struct Tree
{
Tree *lchild;
Tree *rchild;
char data;
};
Tree tree[60];
int loc = 0, n, max;
Tree *creat()
{
tree[loc].lchild = tree[loc].rchild = NULL;
return &tree[loc++];
}
Tree *build(int p1, int p2, int i1, int i2)
{
int i;
Tree *T = creat();
T->data = pre[p1];
for(i = i1; i <= i2; i++)
{
if(in[i] == pre[p1])
break;
}
if(i != i1)
T->lchild = build(p1+1, i - i1 + p1 , i1, i-1);
if(i != i2)
T->rchild = build(p2 + 1 + i - i2, p2, i + 1, i2);
return T;
}
void preOrder(Tree *T, int level)
{
if(T == NULL)
{
if(level > max)
max = level;
return;
}
preOrder(T->lchild, level + 1);
preOrder(T->rchild, level + 1);
}
int main()
{
while(scanf("%d", &n) != EOF)
{
Tree *T = NULL;
scanf("%s", pre);
scanf("%s", in);
T = build(0, n-1, 0, n-1);
max = -1;
preOrder(T, 0);
printf("%d\n", max);
}
return 0;
}
1239

被折叠的 条评论
为什么被折叠?



