1127. ZigZagging on a Tree (30)
来源:互联网 发布:linux jdk1.8 编辑:程序博客网 时间:2024/05/16 12:33
很简单的题,先根据中序排序,与后序排序递归建树,然后层次遍历存入到out数组中,用now存储当前遍历的先后次序,用level来存储当前层数,date存储数据。用sort结构体排序,不同层次按从小到到排。相同层次,如果是奇数层,按now大到小排,如果为偶数层,按now的大小到大排。
#include<iostream> #include<cstdio>#include<vector>#include<cstring>#include<queue>#include<cstdlib>#include<algorithm>using namespace std;struct tree{ int data,level; tree * left; tree *right;};struct node{ int data; int now; int level; friend bool operator < (node a1,node a2) { if(a1.level!=a2.level) return a1.level<a2.level; else { if(a1.level%2) return a1.now>a2.now; else return a1.now<a2.now; } }};vector<int>in,post;vector<node>out;tree * build(int le1,int rig1,int le2,int rig2,int level){ if(le1>rig1) return NULL; int position; for(int i=le1;i<=rig1;i++) if(in[i]==post[rig2]) { position=i; break; } tree *temp; temp=(tree *)malloc(sizeof(tree)); temp->data=post[rig2]; temp->level=level; temp->left=build(le1,position-1,le2,le2+(position-le1-1),level+1); temp->right=build(position+1,rig1,le2+(position-le1),rig2-1,level+1); return temp;}queue<tree *>que;int main(){ int N; cin>>N; for(int i=1;i<=N;i++) { int temp; scanf("%d",&temp); in.push_back(temp); } for(int i=1;i<=N;i++) { int temp; scanf("%d",&temp); post.push_back(temp); } tree * root; root=build(0,N-1,0,N-1,1); que.push(root); int now=1; while(!que.empty()) { tree * temp; temp=que.front(); que.pop(); node n; n.data=temp->data; n.now=now++; n.level=temp->level; out.push_back(n); if(temp->left!=NULL) que.push(temp->left); if(temp->right!=NULL) que.push(temp->right); } sort(out.begin(),out.end()); for(int i=0;i<out.size();i++) { if(i!=0)cout<<" "<<out[i].data; else cout<<out[i].data; } return 0;}
0 0
- 1127. ZigZagging on a Tree (30)
- 1127.ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)
- PAT 1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)
- PAT-1127. ZigZagging on a Tree (30)
- PAT_A 1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30)
- pat 1127. ZigZagging on a Tree (30) 递归建树 + BFS
- PAT 1127. ZigZagging on a Tree (30)-甲级
- PAT (Advanced Level) 1127. ZigZagging on a Tree (30)
- 1127. ZigZagging on a Tree (30) PAT 甲级
- TCP/IP卷1 第3章 IP:网际协议
- 擅长排列的小明STL
- 线性表实现之链表——MyLinkedList
- UVA 1595 Symmetry(对称轴)
- Shell Game_Codeforces
- 1127. ZigZagging on a Tree (30)
- linux运维学习第十三课
- 单片机——51——目录
- java基础面试(2)
- swoole 安装
- PopupWindow,ListView实现自定义Spinner
- Rescue The Princess(计算几何)
- win10修改启动项
- linux运维学习第十四课