L2-006. 树的遍历
L2-006. 树的遍历
时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
根据后序遍历的结果确定根,在中序中找到根的位置,根据中序遍历的结果确定子树的数量,确定数量对应到后序部分,再从后序对应的部分从最后一个确定根.....知道左子树为空。因为不论中序和后序都是从左子树开始的嘛。
在递归的每一层中确定子树的根,存在tree数组。其他填-1,方便遍历。根的左子树根是2*根位置,右子树根是2*根位置+1。
#include <bits/stdc++.h> 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);//递归建右子树,奇数*2 偶数*2加1 } 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; }