PTA Complete Binary Search Tree(完全二叉树的构造)

题目链接

ZJU 数据结构课程04-6构造完全二叉树
https://pintia.cn/problem-sets/951072707007700992/problems/977489256881188864

分析

很简单,自顶向下,递归构造就好 O(nlogn);

code

#include<bits/stdc++.h>
using namespace std;
#define pb push_back
const int maxn = 1e3 +10;
int n;
int a[maxn];
std::vector<int> ans;
std::vector<int> tree[maxn];
void solve(int l,int r,int fa) {
    // std::cout << l << " " << r << '\n';
    if(l==r){
        tree[fa].pb(l);
        return;
    }
    if(l>r)return;
    int num = r -l +1;
    int h = ceil(log2(num+1));
    int left = (1<<h) -1 -num;
    int sz = (num-left-1)/2;
    int last = 1<<(h-2);
    int sz_l = left+ sz;
    if(last < left)sz_l = last+sz;
    tree[fa].pb(l+sz_l);
    solve(l,l+sz_l-1,l+sz_l);
    solve(l+sz_l+1,r,l+sz_l);
}

void bfs(int root) {
    queue<int> Q;
    Q.push(root);
    while (!Q.empty()) {
        int v = Q.front();Q.pop();
        // std::cout << a[v] << '\n';
        ans.pb(a[v]);
        if(tree[v].size()>0){
            for(int e : tree[v]){
                Q.push(e);
            }
        }
    }
}

int main(int argc, char const *argv[]) {
    /* code */
    cin>>n;
    for(int i=1 ; i<=n ; ++i)scanf("%d",a+i );
    sort(a+1,a+n+1);
    solve(1,n,0);
    bfs(tree[0][0]);
    for(int i=0 ; i<ans.size()-1 ; ++i)printf("%d ", ans[i]);
    printf("%d", ans[n-1]);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值