Problem Description
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
Input
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
Output
输出一个整数,即该二叉树的高度。
Example Input
9 ABDFGHIEC FDHGIBEAC
Example Output
5
code:
#include<stdio.h>
#include<stdlib.h>
typedef struct Bitnode
{
char data;
struct Bitnode *lchild, *rchild;
}Bitree;
Bitree *rebuild(char *a, char *b, int n)
{
Bitree *T;
int i;
if(n==0) return NULL;
T = (Bitree*)malloc(sizeof(Bitree));
T->data = a[0];//因为a为前序的序列,故a[0]本就是根节点;
for(i = 0;i<n;i++)//找到中序中第一个和前序相等的元素此时的i指向在a元素中T的右支点的前一个
{
if(b[i] == a[0]) break;
}
T->lchild = rebuild(a+1, b, i);//让向后移动一个,此时的a[0]向后移动,恰好为左支点;
T->rchild = rebuild(a+i+1, b+i+1, n-i-1);//使a与b同时后移i+1个元素,让a指向右结点,不断递归获得原始的树;
return T;
}
int max(int a, int b)
{
if(a>b) return a;
else return b;
}
int hight(Bitree *root)
{
if(root==NULL) return 0;
else return max(hight(root->lchild), hight(root->rchild))+1;
}
int main()
{
int t;
char a[51];
char b[51];
while(~scanf("%d", &t))
{
scanf("%s", a);
scanf("%s", b);
Bitree *T;
T = rebuild(a, b, t);
int hi = hight(T);
printf("%d\n", hi);
}
}
#include<stdlib.h>
typedef struct Bitnode
{
char data;
struct Bitnode *lchild, *rchild;
}Bitree;
Bitree *rebuild(char *a, char *b, int n)
{
Bitree *T;
int i;
if(n==0) return NULL;
T = (Bitree*)malloc(sizeof(Bitree));
T->data = a[0];//因为a为前序的序列,故a[0]本就是根节点;
for(i = 0;i<n;i++)//找到中序中第一个和前序相等的元素此时的i指向在a元素中T的右支点的前一个
{
if(b[i] == a[0]) break;
}
T->lchild = rebuild(a+1, b, i);//让向后移动一个,此时的a[0]向后移动,恰好为左支点;
T->rchild = rebuild(a+i+1, b+i+1, n-i-1);//使a与b同时后移i+1个元素,让a指向右结点,不断递归获得原始的树;
return T;
}
int max(int a, int b)
{
if(a>b) return a;
else return b;
}
int hight(Bitree *root)
{
if(root==NULL) return 0;
else return max(hight(root->lchild), hight(root->rchild))+1;
}
int main()
{
int t;
char a[51];
char b[51];
while(~scanf("%d", &t))
{
scanf("%s", a);
scanf("%s", b);
Bitree *T;
T = rebuild(a, b, t);
int hi = hight(T);
printf("%d\n", hi);
}
}