Problem Description
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
Input
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
Output
输出一个整数,即该二叉树的高度。
Sample Input
9
ABDFGHIEC
FDHGIBEAC
Sample Output
5
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
#define INF 0x3f3f3f3f
using namespace std;
struct node
{
int data;
struct node *l;
struct node *r;
};
struct node *create(int n,int a[],int b[])
{
struct node *root = NULL;
if(n==0)
return NULL;
else
{
root = (struct node *)malloc(sizeof(struct node));
root->data = b[n-1];
int j = 0;
for(int i=0;i<n;i++)
{
if(a[i]==b[n-1])
{
j = i;
break;
}
}
root->l = create(j,a,b);
root->r = create(n-j-1,a+j+1,b+j);
}
return root;
}
void ceng(struct node *root)
{
struct node *temp[60];
int in = 0;
int out = 0;
int c[60];
int j = 0;
temp[in++] = root;
while(in>out)
{
if(temp[out])
{
c[j++] = temp[out]->data;
///一定要注意这里,以前没有遇到过这种情况,如果用数组模拟的话,需要开两倍的空间。
///因为叶子结点也符合条件,所以叶子结点的孩子虽然为空,但是也要入队列。
///所以需要多n+1个空间。
temp[in++] = temp[out]->l;
temp[in++] = temp[out]->r;
}
out++;
}
for(int i=0;i<j;i++)
printf(i==j-1?"%d\n":"%d ",c[i]);
}
int main()
{
int n;
int a[550];
int b[550];
struct node *root = NULL;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&b[i]);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
root = create(n,a,b);
if(root)
ceng(root);
return 0;
}