当前位置: 首页 > news >正文

Z 字形遍历二叉树

假设一个二叉树上各结点的权值互不相同。

我们就可以通过其后序遍历和中序遍历来确定唯一二叉树。

请你输出该二叉树的 ZZ 字形遍历序列----也就是说,从根结点开始,逐层遍历,第一层从右到左遍历,第二层从左到右遍历,第三层从右到左遍历,以此类推。

例如,下图所示二叉树,其 ZZ 字形遍历序列应该为:1 11 5 8 17 12 20 15

337cbfb0-a7b2-4500-9664-318e9ffc870e.jpg

输入格式

第一行包含整数 NN,表示二叉树结点数量。

第二行包含 NN 个整数,表示二叉树的中序遍历序列。

第三行包含 NN 个整数,表示二叉树的后序遍历序列。

输出格式

输出二叉树的 ZZ 字形遍历序列。

数据范围

1≤N≤301≤N≤30

输入样例:
8
12 11 20 17 1 15 8 5
12 20 17 11 15 8 5 1
输出样例:
1 11 5 8 17 12 20 15
#include <iostream>
#include <cstring>
#include <map>
#include <queue>
#include <algorithm>
#include <vector>
using namespace std;
const int N=40;
int inorder[N],postorder[N];
int n;
int depth[N];
map<int,int>l,r,pos;    vector<int>res;
int  build(int il,int ir,int pl,int pr)
{if(il>ir)    return 0 ;int root=postorder[pr];    int k=pos[root];if(il<k)   l[root]=build(il,k-1,pl,pl+k-1-il); if(ir>k)    r[root]=build(k+1,ir,pl+k-il,pr-1);// cout<<root<<" "<< l[root]<<" "<<r[root]<<endl;return root;
}void bfs(int root)
{  queue<int>q;q.push(root);int st=1;int flag=0;while(!q.empty()){int size=q.size();for(int i=0;i<size;i++){auto t=q.front();res.push_back(t);q.pop();if(l[t])    q.push(l[t]);if(r[t])    q.push(r[t]);}if(!flag)    reverse(res.begin()+res.size()-size,res.end());flag=!flag;}
}
int main()
{cin>>n;// memset(l,-1,sizeof(l));// memset(r,-1,sizeof(r));for(int i=0;i<n;i++)    cin>>inorder[i],pos[inorder[i]]=i;for(int i=0;i<n;i++)    cin>>postorder[i];int root= build(0,n-1,0,n-1);bfs(root);// int root=postorder[n-1];cout<<res[0];for(int i=1;i<n;i++)    cout<<" "<<res[i];
}

http://www.lryc.cn/news/422826.html

相关文章:

  • [Vue]Vue3从入门到精通-综合案例分析
  • 深度学习——神经网络(neural network)详解(二). 带手算步骤,步骤清晰0基础可看
  • 【扒网络架构】backbone、ccff
  • linux进程
  • PRVF-4037 : CRS is not installed on any of the nodes
  • 整理 酷炫 Flutter 开源UI框架 FAB
  • Unity 编写自己的aar库,接收Android广播(broadcastReceiver)并传递到Unity
  • Mysql cast函数、cast用法、字符串转数字、字符串转日期、数据类型转换
  • 微信小程序开发之组件复用机制
  • 数据结构--线性表
  • 深入探针:PHP与DTrace的动态追踪艺术
  • 黑龙江日报报道第5届中国计算机应用技术大赛,赛氪提供赛事支持
  • 【计算机网络】LVS四层负载均衡器
  • Java 守护线程练习 (2024.8.12)
  • C#小桌面程序调试出错,如何解决??
  • Seatunnel Mysql数据同步到Mysql
  • Java Web —— 第五天(请求响应1)
  • 【LLMOps】手摸手教你把 Dify 接入微信生态
  • Ftrans文件摆渡方案:重塑文件传输与管控的科技先锋
  • LaTeX中的除号表示方法详解
  • DID、DID文档、VC、VP分别是什么 有什么关系
  • 网络安全应急响应
  • Qt数据和视图分离——中MCV和MVVM
  • 重定义变量类型:如#define FLOAT float和typedef float FLOAT的区别
  • Qt 使用阿里矢量图标库
  • 仓颉语言运行时轻量化实践
  • 深入理解Python中的subprocess模块
  • 从零开始搭建 EMQX 集群压测框架
  • ArkUI基本介绍
  • vue2+OpenLayers 天地图上打点并且显示相关的信息(2)