L2-006. 树的遍历(利用后序中序还原二叉树)
来源:互联网 发布:易企秀一样的软件 编辑:程序博客网 时间:2024/05/16 14:38
题目链接: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;
- }
阅读全文
1 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. 树的遍历
- Java开发异常处理
- 代码干货|Python API快餐教程(1)
- 【数据结构】LinkedList原理及实现学习总结
- B
- C#中string转成int类型
- L2-006. 树的遍历(利用后序中序还原二叉树)
- RSAUtil
- hihoCoder #1000:A+B (大整数)题解
- Java就业指导
- webdriver浏览器的部分属性
- 高德地图的使用之自动定位和marker的点击显示自定义PopupWindow
- Windows下修改MySQL编码为utf8
- oracle 基础知识 一
- MySQL中文乱码问题