标签:ack tle put 假设 title std can vector efi
输入第一行给出一个正整数N
(≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
input:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
output:
4 6 1 7 5 3 2
#include<cstdio> #include<iostream> #include<algorithm> #include<string> #include<queue> #include<cmath> #include<vector> #include<cstdlib> using namespace std; #define long long ll const int maxn = 100 + 5; int zhong[maxn],qian[maxn]; struct node { int l,r; }a[maxn]; int build(int la,int ra,int lb,int rb) { if(la > ra) return 0; int rt = qian[lb]; int posrt = la; while(zhong[posrt] != rt) posrt++; int l = posrt - la; a[rt].l = build(la,la + l - 1,lb + 1,lb + l); a[rt].r = build(posrt + 1,ra,lb + l + 1,rb); return rt; } void bfs(int x) { queue<int>que; vector<int>vec; que.push(x); while(!que.empty()) { int tmp = que.front(); que.pop(); if(tmp == 0) break; vec.push_back(tmp); if(a[tmp].r != 0) que.push(a[tmp].r); if(a[tmp].l != 0) que.push(a[tmp].l); } for(int i=0;i<vec.size();i++) printf("%d%c",vec[i],i == (vec.size() - 1) ? ‘\n‘ : ‘ ‘); } int main() { int n; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&zhong[i]); for(int i=1;i<=n;i++) scanf("%d",&qian[i]); build(1,n,1,n); int root = qian[1]; bfs(root); }
标签:ack tle put 假设 title std can vector efi
原文地址:https://www.cnblogs.com/smallhester/p/10569006.html