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