您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树四:(先序中序)还原二叉树

2018-02-01 14:20 483 查看


Problem Description

给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。


Input

输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。


Output

输出一个整数,即该二叉树的高度。


Example Input

9
ABDFGHIEC
FDHGIBEAC



Example Output

5


01
#include<stdio.h>
02
#include<stdlib.h>
03
#include<string.h>
04
struct
node
05
{
06
char
date;
07
struct
node
*l, *r;
08
};
09
char
a[55],
b[55];
10
struct
node
*creat(
int
n,
char
a[],
char
b[])
11
{
12
struct
node
*root;
13
if
(n
== 0)
return
NULL;
14
root
= (
struct
node
*)
malloc
(
sizeof
(
struct
node));
15
root->date
= a[0];
16
int
i;
17
for
(i
= 0; i < n; i++)
18
{
19
if
(a[0]
== b[i])
20
break
;
21
}
22
root->l
= creat(i, a+1, b);
23
root->r
= creat(n-1-i, a+1+i, b+1+i);
24
return
root;
25
}
26
27
int
high(
struct
node
*root)
28
{
29
int
h,
lh, rh;
30
if
(root
== NULL) h = 0;
31
else
32
{
33
lh
= high(root->l);
34
rh
= high(root->r);
35
if
(lh>rh)
36
h
= lh+1;
37
else
38
h
= rh+1;
39
}
40
return
h;
41
}
42
int
main()
43
{
44
int
n,
h;
45
while
(
scanf
(
"%d"
,
&n) != EOF)
46
{
47
struct
node
*root;
48
scanf
(
"%s%s"
,
a, b);
49
root
= creat(n,a, b);
50
h
= high(root);
51
printf
(
"%d\n"
,
h);
52
}
53
return
0;
54
}
55
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: