数据结构实验之二叉树四:(先序中序)还原二叉树
Time Limit: 1000 ms
Memory Limit: 65536 KiB
Problem Description
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
Input
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
Output
输出一个整数,即该二叉树的高度。
Sample Input
9 ABDFGHIEC FDHGIBEAC
Sample Output
5
Hint
#include<bits/stdc++.h>
using namespace std;
char a[55], b[55];
struct node
{
char da;
node *l, *r;
};
node *creat(char a[], char b[], int n)
{
int i;
if(n==0) return NULL;
node *root;
root = new node;
root->da = a[0];
for(i = 0; i < n; i++)
{
if(b[i]==a[0])
break;
}
root->l = creat(a+1, b, i);
root->r = creat(a+i+1, b+i+1, n-i-1);
return root;
}
int depth(node *root)
{
if(!root) return 0;
return depth(root->l)>depth(root->r)?depth(root->l)+1:depth(root->r)+1;
}
int main()
{
int n, k;
node *root;
while(~scanf("%d", &n))
{
scanf("%s", a);
scanf("%s", b);
root = creat(a, b, n);
k = depth(root);
printf("%d\n", k);
}
}