0
点赞
收藏
分享

微信扫一扫

【PAT甲级】1064 Complete Binary Search Tree

忍禁 2022-03-30 阅读 81

1.二叉搜索树中序遍历是有序序列
2.完全二叉树可由数组模拟,左子树为2n,右子树为2n+1

#include <bits/stdc++.h>

using namespace std;

const int N = 1010;
int n;
int w[N], tr[N];
int cnt;

void dfs(int u)
{
    if(2 * u <= n) dfs(2 * u);
    tr[u] = w[cnt ++];
    if(2 * u + 1 <= n) dfs(2 * u + 1);
}

int main()
{
    cin >> n;
    for(int i = 1; i <= n; i ++) cin >> w[i];
    sort(w + 1, w + n + 1);

    cnt = 1;
    dfs(1);

    cout << tr[1];
    for(int i = 2; i <= n; i ++) cout << ' ' << tr[i];
}
举报

相关推荐

0 条评论