题目链接:https://www.patest.cn/contests/gplt/L2-006
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。 输入格式: 输入第一行给出一个正整数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<iostream> #include<stdio.h> #include<string.h> #include<stdlib.h> #include<stack> #include<vector> #include<string> #include<algorithm> #include<queue> using namespace std; const int N=1100; #define met(a,b) memset(a,b,sizeof(a)) int a[N],b[N]; int tree[N]; int sum[N]; void build(int n,int la,int ra,int lb,int rb)///利用递归的方法建立二叉树 { if(ra<la ||rb<lb) return ; if(la==ra) { tree[n]=a[la]; return ; } for(int i=la; i<=ra; i++) { if(a[i]==b[rb])///后序遍历的最右边的为根节点,找到根节点在中序遍历的位置, ///该位置的后边的点为左子树,后边为右之树,以这个原理递归下去 { tree[n]=b[rb]; build(2*n,la,i-1,lb,lb+i-1-la); build(2*n+1,i+1,ra,lb+i-la,rb-1); break; } } } void bfs(int s) { queue<int>Q; Q.push(s); int ans=1; while(Q.size()) { int y=Q.front(); Q.pop(); if(tree[y]==0) continue; sum[ans++]=tree[y]; Q.push(2*y); Q.push(2*y+1); } } int main() { int n; met(tree,0); scanf("%d",&n); for(int i=1; i<=n; i++) { scanf("%d",&b[i]); } for(int i=1; i<=n; i++) { scanf("%d",&a[i]); } build(1,1,n,1,n); bfs(1); for(int i=1;i<=n;i++) { printf("%d%c",sum[i],i==n?'\n':' '); } return 0; }