L2-035 完全二叉树的层序遍历

随便刷几个天梯赛题目。

  原题在这里

  概述题意,给定完全二叉树的后序遍历,问层序遍历结果。

analyse:

  1.刚开始很认真的逆序建树,写得不是很顺畅,因为我不喜欢这种数据关系类型的题目。

code:

#include <bits/stdc++.h>
using namespace std;
#define Mx 2022
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define cn(s) cout << s << endl
typedef long long ll;
struct ii
{
    int x;
    int left, right;
} node[Mx];
int a[Mx];
//后往前则为:根右左,二分处理
void Build(int x, int l, int r) //后序遍历结果序号x
{
    if (l > r)
        return;
    int num = 0, id = 1, mid;
    while (num + id < r - l)
    {
        num += id;
        id += id;
    }
    mid = max(r - l - num, num);
    //保证mid区分左右子树之一为完全二叉树即可(左子树优先取max)
    node[x].x = r;

    if (l == r)
        return;
    node[x].left = l + mid - 1;

    if (mid > r - 1)
        return;
    node[x].right = r - 1;

    Build(x * 2, l, l + mid - 1);
    Build(x * 2 + 1, l + mid, r - 1);
}
int main()
{
    IOS;
    // Solution s;
    // L2-035 完全二叉树的层序遍历
    int n;
    cin >> n;
    for (int i = 1; i <= n; ++i)
        cin >> a[i];
    Build(1, 1, n);
    for (int i = 1; i <= n; ++i)
        cout << a[node[i].x] << (i == n ? '\n' : ' ');
    return 0;
}
21(25满分)

居然分没得全,怪哉,没想到有什么bug的地方了。

  2.dfs模拟后序遍历建树

code:

#include <bits/stdc++.h>
using namespace std;
#define Mx 2022
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define cn(s) cout << s << endl
typedef long long ll;
int node[Mx];
int a[Mx], n, id = 0;
void dfs(int x)
{
    if (x <= n)
    {
        dfs(x << 1);
        dfs(x << 1 | 1);
        node[x] = a[++id];
    }
}
int main()
{
    IOS;
    // L2-035 完全二叉树的层序遍历
    cin >> n;
    for (int i = 1; i <= n; ++i)
        cin >> a[i];
    dfs(1);
    for (int i = 1; i <= n; ++i)
        cout << node[i] << (i == n ? '\n' : ' ');
    return 0;
}

 

【Over

posted @ 2022-04-22 21:18  Renhr  阅读(65)  评论(0)    收藏  举报