7-1 还原二叉树 (25 分)
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
结尾无空行
输出样例:
5
结尾无空行
c代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct TreeNode
{
char data;
struct TreeNode *lchild, *rchild;
}BTnode,*BinTree;
BinTree creatTree(char a[], char b[], int len) //先序和中序建树
{
BinTree BT;
int i;
if(len == 0)
return NULL;
BT = (BinTree)malloc(sizeof(BTnode));
BT->data = a[0];
for(i = 0; i < len; i++)
{
if(b[i] == a[0])
break;
}
BT->lchild = creatTree(a + 1, b, i);
BT->rchild = creatTree(a + 1 + i, b + i + 1, len - i - 1);
return BT;
}
int getTree(BinTree BT)
{
int HL, HR, height;
if(BT == 0)
return 0;
HL = getTree(BT->lchild);
HR = getTree(BT->rchild);
height = (HL > HR ? HL : HR) + 1;
return height;
}
int main()
{
int n;
char a1[51], a2[51];
scanf("%d",&n);
scanf("%s %s",a1, a2);
BinTree bt = creatTree(a1, a2, n);
int result = getTree(bt);
printf("%d",result);
return 0;
}
看的大佬的代码(没用树,但很简洁)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int getHeight(char *a, char *b, int len)
{
int i, LH, RH;
if(len == 0)
return 0;
else
{
for(i = 0; i < len; i++)
if(b[i] == a[0]) break;
LH = getHeight(a + 1, b, i);
RH = getHeight(a + 1 + i, b + 1 + i, len - i - 1);
return (LH > RH ? LH : RH) + 1;
}
}
int main()
{
int n;
char arr1[51],arr2[51];
scanf("%d",&n);
scanf("%s %s",arr1, arr2);
printf("%d",getHeight(arr1, arr2, n));
return 0;
}