给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
结尾无空行
输出样例:
5
结尾无空行
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct TNode* Position;
typedef Position BinTree;
struct TNode {
char Data;
BinTree Left;
BinTree Right;
};
BinTree CreatBinTree(char* pre, char* mid, int len) {
if (len <= 0)return NULL;
BinTree bt;
int k;
char root = pre[0];
bt = (BinTree)malloc(sizeof(struct TNode));
bt->Data = root;
for (k = 0; k < len; k++) {
if (root == mid[k])
break;
}
bt->Left = CreatBinTree(pre + 1, mid, k);
bt->Right = CreatBinTree(pre + 1 + k, mid + 1 + k, len - 1 - k);
return bt;
}
int GetHeight(BinTree BT) {
int HL, HR, MaxH;
if (BT) {
HL = GetHeight(BT->Left);
HR = GetHeight(BT->Right);
MaxH = HL > HR ? HL : HR;
return(MaxH + 1);
}
else return 0;
}
int main() {
int len;
int Height;
BinTree BT;
scanf("%d", &len);
char pre[52] = {0};
char mid[52] = {0};
scanf("%s", pre);
scanf("%s", mid);
len = strlen(mid);
BT = CreatBinTree(pre, mid, len);
Height = GetHeight(BT);
printf("%d", Height);
system("pause");
return 0;
}