当前位置:网站首页>还原二叉树 (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
边栏推荐
猜你喜欢
Shell脚本进阶
Excle plus watermark
idea打包 jar文件
Shell script advanced
洋桃电子STM32物联网入门30步笔记四、工程编译和下载
四张图弄懂matplotlib的一些基本用法
Harbor企业级镜像管理系统实战
Idea import commons-logging-1.2 Jar package
虚拟线上展会-线上vr展馆实现24h沉浸式看展
Yangtao electronic STM32 Internet of things entry 30 step notes II. Cube ide download, installation, sinicization and setting
随机推荐
怎样读取Excel表格到数据库
Notes on 30 steps of introduction to the Internet of things of yangtao electronics STM32 III. cubemx graphical programming and setting the IO port on the development board
Redis master-slave server problem
rembg 分割mask
Asan minimalism
对li类数组对象随机添加特性,并进行排序
程序,进程,线程;内存结构图;线程的创建和启动;Thread的常用方法
idea打包 jar文件
Stm32f103zet6 [development of standard library functions] - Introduction to library functions
数据可视化:使用Excel制作雷达图
idea配置连接远程数据库MySQL,或者是Navicat连接远程数据库失败问题(已解决)
DJ音乐管理软件Pioneer DJ rekordbox
Trust uses Tokio's notify and timeout to achieve the effect similar to the timeout condition variable
Shell script advanced
CGM optimizes blood glucose monitoring and management -- Yiyu technology appears in Sichuan International Medical Exchange Promotion Association
LINQ Learning Series ----- 1.4 anonymous objects
Virtual online exhibition - Online VR exhibition hall realizes 24h immersive exhibition viewing
Navicat remote connection MySQL
PgSQL wants to implement all kinds of column sub query operations of MySQL
经典题目刷一刷