7-23 还原二叉树 (25 分)
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
代码如下
#include<bits/stdc++.h>
using namespace std;
typedef struct tnode* tree;
struct tnode
{
char data;
tree left;
tree right;
};
char pre[50], mid[50];
tree build(int n, char pre[], char mid[])
{
if (n <= 0)
return NULL;
char* p = mid;
while (p)
{
if (*p == pre[0])
break;
p++;
}
int zuo = p - mid;
tree L = (tree)malloc(sizeof(struct tnode));
L->data = pre[0];
L->left = build(zuo, pre + 1, mid);
L->right = build(n - zuo - 1, pre + zuo + 1, mid + zuo + 1);
return L;
}
int height(tree L)
{
if (L == NULL)
return 0;
else
{
int maxnum = max(height(L->left), height(L->right));
return (1 + maxnum);
}
}
int main()
{
int n;
cin >> n >> pre >> mid;
tree L = build(n, pre, mid);
cout << height(L) << endl;
}