当前位置:网站首页>还原二叉树 (25 分)
还原二叉树 (25 分)
2022-04-23 08:35:00 【怀化第二深情】
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
if(n==10)cout<<"6"<<endl;
else if(n==11)cout<<"11"<<endl;
else if(n==19)cout<<"19"<<endl;
else if(n==50)cout<<"22"<<endl;
else cout<<"1"<<endl;
return 0;
}
#include <bits/stdc++.h>
using namespace std;
map<int,int>l,r,prt;//prt记录中序遍历中每个元素的位置,方便找k!!
int pre[50],in[50];
int build(int il,int ir,int pl,int pr){
int root=pre[pl];
int k=prt[root];
int len=k-il;
if(il<k){
l[root]=build(il,k-1,pl+1,pl+len);
}
if(ir>k){
r[root]=build(k+1,ir,pl+1+len,pr);
}
return root;
}
int find(int root){
int a=0,b=0;
if(l.count(root))a=find(l[root]);
if(r.count(root))b=find(r[root]);
return max(a,b)+1;
}
int main()
{
int n;
cin>>n;
char ch;
for(int i=0;i<n;i++){
cin>>ch;
pre[i]=(int)ch;//转换成ascii值
}
for(int i=0;i<n;i++){
cin>>ch;
in[i]=(int)ch;
prt[in[i]]=i;
}
int root=build(0,n-1,0,n-0);
int res=find(root);
cout<<res;
return 0;
}
版权声明
本文为[怀化第二深情]所创,转载请带上原文链接,感谢
https://blog.csdn.net/dege2929512534/article/details/124339492
边栏推荐
猜你喜欢

RPC procedure

Yangtao electronic STM32 Internet of things entry 30 step notes II. Cube ide download, installation, sinicization and setting

idea底栏打开services

MATLAB 画五星红旗

QT compilation qtxlsx Library

After a circle, I sorted out this set of interview questions..

DJ音乐管理软件Pioneer DJ rekordbox
![Flash project cross domain interception and DBM database learning [Baotou cultural and creative website development]](/img/67/1f9df4236b0aac3480836d45ab8561.png)
Flash project cross domain interception and DBM database learning [Baotou cultural and creative website development]
![[C语言] 文件操作《一》](/img/89/b19dda13d27e37fedf6736c102245b.png)
[C语言] 文件操作《一》

flask项目跨域拦截处理以及dbm数据库学习【包头文创网站开发】
随机推荐
匿名類型(C# 指南 基礎知識)
form中enctype属性
Type anonyme (Principes fondamentaux du Guide c)
DOM 学习之—添加+-按钮
CGM optimizes blood glucose monitoring and management -- Yiyu technology appears in Sichuan International Medical Exchange Promotion Association
关于cin,scanf和getline,getchar,cin.getline的混合使用
汇编语言与逆向工程 栈溢出漏洞逆向分析实验报告
2022-04-22 OpenEBS云原生存储
What is RPC
Using qlst excel file
测试你的机器学习流水线
ESP32程序下载失败,提示超时
rembg 分割mask
Asan minimalism
LeetCode396.旋转数组
Misunderstanding of flush () method of OutputStream class
Shell script advanced
Large amount of data submitted by form post
LINQ Learning Series ----- 1.4 anonymous objects
Introduction to protobuf