CCCC的一道模拟题,挺常见的,但是之前对数据结构一直松懈,赶紧补补。
二叉树各种遍历的关键在于一个子树不管在哪种遍历中都是连续出现的。
所以可以利用不同遍历的顺序确定哪一段是左子树,哪一段是右子树。(所以必须要有中序遍历才能做)
代码是用的恒神的。用数组模拟树,递归也写的很漂亮。
L2-2. 树的遍历
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:7 2 3 1 5 7 6 4 1 2 3 4 5 6 7输出样例:
4 1 6 3 5 7 2
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5; int n; int post[maxn]; int mid[maxn]; int tree[maxn]; int mk(int l,int r,int L,int R,int id)//lr是后序的,LR是中序遍历的 { if(r<=l&&R<=L) return post[r]; int rt=post[r]; //后序遍历的最后一个,必然是中间的那个节点 int pos; for(int i=L;i<=R;i++) if(mid[i]==rt) { pos=i;break; //找到中间节点在中序遍历中的位置,这样其左边的必为左子树,右边必为右子树,然后递归求解就行了 } int lc=pos-L,rc=R-pos; if(lc==0) tree[id<<1]=-1;//此时到达叶子节点,要特判 else { tree[id<<1]=mk(l,l+lc-1,L,L+lc-1,id<<1); } if(rc==0) tree[id<<1|1]=-1; else { tree[id<<1|1]=mk(l+lc,l+lc+rc-1,pos+1,R,id<<1|1); } return rt; } int main() { freopen("in.txt","r",stdin); memset(tree,0,sizeof(tree)); cin>>n; for(int i=0;i<n;i++) cin>>post[i]; for(int i=0;i<n;i++) cin>>mid[i]; tree[1]=mk(0,n-1,0,n-1,1); cout<<tree[1]<<endl; queue<int >que; vector<int>v; que.push(1); while(!que.empty()) { int a=que.front();que.pop(); v.push_back(tree[a]); if(tree[a<<1]>0)que.push(a<<1); if(tree[a<<1|1]>0)que.push(a<<1|1); } for(int i=0;i<v.size();i++) { if(!i) cout<<v[i]; else cout<<" "<<v[i]; } return 0; }