7-1 还原二叉树 分数 25
作者 DS课程组
单位 浙江大学
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n; // 节点数
char pre[N]; // 先序遍历得到的的序列
char mid[N]; // 中序遍历得到的的序列
struct node
{
char data; //节点的数据
node *l, *r; //左孩子,右孩子
};
node *build(int len, char *pre, char *mid) //建树
{
node *root = new node;
if (!len)
return NULL; // 返回空节点
root->data = pre[0]; // pre[0]为根节点
int i;
for (i = 0; i < len; i++)
{
if (mid[i] == pre[0]) // 在中序遍历中找到根节点
break;
}
root->l = build(i, pre + 1, mid); // 建立左子树
root->r = build(len - i - 1, pre + i + 1, mid + i + 1); // 建立右子树
return root;
}
int get_high(node *root) //求树的高度
{
int res = 0;
int hl = 0, hr = 0; //初始化左子树高度和右子树高度
if (!root) //节点为空,高度为0
res = 0;
else
{
hl = get_high(root->l); // 左子树高度
hr = get_high(root->r); // 右子树高度
res = max(hl, hr) + 1; // 最高子树高度+1个根节点
}
return res; // 返回高度
}
int main()
{
cin >> n;
cin >> pre >> mid;
node *root = build(n, pre, mid); // 建树
cout << get_high(root) << endl; // 输出高度
return 0;
}