给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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>
#define ll long long
#define PI acos(-1)
#define mes(x,y) memset(x,y,sizeof(x))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
const ll inf = 2e9 + 10;
const ll mod = 1e10 + 7;
const ll MAXN = 2e10 + 10;
ll n, m, i, j, t, w, sum;
ll a[31], flagb[31], po[1785];
void buildtree(ll th, ll bea, ll ena, ll beb, ll enb) {
po[th] = a[ena];
if (flagb[po[th]] != beb) {
ll len = flagb[po[th]] - beb;
buildtree(2 * th, bea, bea + len - 1, beb, flagb[po[th]] - 1);
}//根据中序遍历确定有左子树
if (flagb[po[th]] != enb) {
ll len = enb - flagb[po[th]];
buildtree(2 * th + 1, ena - len, ena - 1, flagb[po[th]] + 1, enb);
}//根据中序遍历确定有右子树
}
vector<ll>v[31];
void frontbianli(ll th, ll step) {
v[step].push_back(po[th]); sum = max(sum, step);
if (po[2 * th] != 0)frontbianli(2 * th, step + 1);
if (po[2 * th + 1] != 0)frontbianli(2 * th + 1, step + 1);
}
int main() {
while (cin >> n) {
for (mes(po, 0), sum = 0, i = 1; i <= n; i++)cin >> a[i], v[i].clear();
for (i = 1; i <= n; i++)cin >> j, flagb[j] = i;
vector<ll>re;
for (buildtree(1, 1, n, 1, n), frontbianli(1, 1), i = 1; i <= sum; i++)
for (j = 0; j < v[i].size(); j++)re.push_back(v[i][j]);
for (i = 0; i < n - 1; i++)cout << re[i] << " ";
cout << re[i] << endl;
}
}
代码2.0:
#include<bits/stdc++.h>
#define ll long long
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
const ll MAXN = 1e12 + 10;
ll n, m, i, j, k, t, w, x, y, z, in, flag, cou, sum, maxn, minn;
string s, s1, s2;
const ll INF = 1e9 + 7;
ll* Buildtree ( ll hl, ll hr, ll *hx, ll zl, ll *mm, ll *re )
{
*re = hx[hr];
ll llen = mm[hx[hr]] - zl, rlen = hr - hl - llen;
if ( llen ) re = Buildtree ( hl, hl + llen - 1, hx, zl, mm, re + 1 );
if ( rlen ) re = Buildtree ( hr - rlen, hr - 1, hx, mm[hx[hr]] + 1, mm, re + 1 );
return re;
}
int main()
{
ll re[31], hx[31], mm[31] = {0};
for ( cin >> n, i = 0; i < n; i++ ) cin >> hx[i];
for ( i = 0; i < n; i++ ) cin >> j, mm[j] = i;
for ( cout << "Preorder:", Buildtree ( 0, n - 1, hx, 0, mm, re ), i = 0; i < n; i++ ) cout << " " << re[i] ;
return 0;
}