L2-006. 树的遍历(利用后序中序还原二叉树)
来源:互联网 发布:linux版本查看命令 编辑:程序博客网 时间:2024/05/16 18:24
题目链接:https://www.patest.cn/contests/gplt/L2-006
思路分析:后序可以知道树根,然后在中序中找出树根,又可以确定左右子树,然后递归地对左右子树进行分解,即可还原出二叉树。最后把建好的树BFS一遍就可以写出层次遍历了。
AC代码如下:
#include<iostream>#include<vector>#include<queue>#include<cstring>#include<cstdio>using namespace std;const int maxn=3005;int tree[maxn];void build(int rt,vector<int>a,vector<int>b)//递归建树{ if(a.size()==0) return ;//递归出口 int p=0; for(int i=0;i<b.size();i++)//找出根 if(b[i]==a[a.size()-1]) p=i; vector<int>al,ar,bl,br; for(int i=0;i<p;i++) al.push_back(a[i]);//左子树的后序遍历序列 for(int i=p;i<a.size()-1;i++) ar.push_back(a[i]);//右子树的后序遍历序列 for(int i=0;i<p;i++) bl.push_back(b[i]);//左子树的中序遍历序列 for(int i=p+1;i<b.size();i++) br.push_back(b[i]);//右子树的中序遍历序列 tree[rt]=b[p];//建根 build(rt<<1,al,bl);//递归建左子树 build(rt<<1|1,ar,br);//递归建右子树}void bfs()//用bfs层次遍历{ queue<int>q; int root=1; q.push(root); int f=0; while(q.size()) { if(f++) cout<<" "; root=q.front(); cout<<tree[root]; q.pop(); if(tree[root<<1]!=-1) q.push(root<<1); if(tree[root<<1|1]!=-1) q.push(root<<1|1); } cout<<endl;}int main(){ //freopen("in.txt","r",stdin); int n,x; while(cin>>n) { memset(tree,-1,sizeof(tree)); vector<int>a,b; for(int i=0;i<n;i++) cin>>x,a.push_back(x); for(int i=0;i<n;i++) cin>>x,b.push_back(x); build(1,a,b); bfs(); } return 0;}
0 0
- L2-006. 树的遍历(利用后序中序还原二叉树)
- L2-006. 树的遍历(利用后序中序还原二叉树)
- L2-006. 树的遍历(后序 中序 还原)
- PAT L2-006. 树的遍历(二叉树重构)
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- CentOS7安装GNOME图形界面
- 在linux (CentOs7)上安装Postgres-xc
- 基于STM32F429-Discovery RTEMS 4.11的移植
- 第十一周——实现类中的运算符重载
- UVALive - 4264 Message (模拟)
- L2-006. 树的遍历(利用后序中序还原二叉树)
- 一个毕业设计 小学生英语app
- 模拟最短路径寻路(JAVA界面)
- pcre.h: No such file or directory
- ios使用内存管理工具
- 第11周—— 存储班长信息的学生类
- 构建集群的基础理论
- springmvc + hibernate + mysql + maven 简单应用
- 新的开始!!!!!