给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
#include<bits/stdc++.h>
using namespace std;
int dfs(string pre, string in, int n) {
int i = 0;
if (n == 0)
return 0;
else {
while (in[i] != pre[0])
i++;
}
int left = dfs(pre.substr(1,i), in.substr(0,i), i);
int right = dfs(pre.substr(i + 1), in.substr(i + 1), n - i - 1);
return max(left , right)+1;
}
int main() {
int n;
cin >> n;
string a, b;
cin >> a >> b;
cout << dfs(a, b, n);
return 0;
}