给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9 ABDFGHIEC FDHGIBEAC
输出样例:
5
二叉树序列转换,请点击这里:https://www.mmuaa.com/post/ee2b491b9925cb5a.html
代码如下:
#include <cstdio>
#include <algorithm>
#include <queue>
#define MAXN 51
using namespace std;
typedef struct _node{
char data;
_node *lchild, *rchild;
int layer;
} node;
char preorder[MAXN], inorder[MAXN];
int n;
node* create(int preL, int preR, int inL, int inR){
if(preL > preR) return NULL;
//计算偏移量
int root_index = find(inorder, inorder + n, preorder[preL]) - inorder,
length_lchild = root_index - inL;
int new_L_preL = preL + 1,
new_L_preR = preL + length_lchild,
new_L_inL = inL,
new_L_inR = root_index - 1;
int new_R_preL = new_L_preL + length_lchild,
new_R_preR = preR,
new_R_inL = root_index + 1,
new_R_inR = inR;
//写根节点
node* root = new node;
root->data = preorder[preL];
//递归建树
root->lchild = create(new_L_preL, new_L_preR, new_L_inL, new_L_inR);
root->rchild = create(new_R_preL, new_R_preR, new_R_inL, new_R_inR);
return root;
}
int layerorder(node* root){
queue<node*> Q;
root->layer = 1;
int max_layer = 0;
Q.push(root);
while(!Q.empty()){
node* iter = Q.front();
Q.pop();
if(iter->layer > max_layer) max_layer = iter->layer;
if(iter->lchild){
iter->lchild->layer = iter->layer + 1;
Q.push(iter->lchild);
}
if(iter->rchild){
iter->rchild->layer = iter->layer + 1;
Q.push(iter->rchild);
}
}
return max_layer;
}
int main(){
scanf("%d", &n);
getchar(); //吸收回车
for(int i = 0; i < n; i++)
scanf("%1c", &preorder[i]);
getchar(); //吸收回车
for(int i =0; i < n; i++)
scanf("%1c", &inorder[i]);
node* root = create(0, n-1, 0, n-1);
printf("%d\n", layerorder(root));
return 0;
}