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

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  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值