栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

PAT (Advanced Level) Practice 1167 Cartesian Tree

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PAT (Advanced Level) Practice 1167 Cartesian Tree

题目

堆是一棵完全二叉树,树中每个结点的值都不小于(或不大于)其左右孩子结点的值。

这是一道简单题。但是,本菜鸡对于堆的定义不了解。所以,卡住了。而且,这应该是本菜鸡第一次用指针的写法,完成的一道题目。

#include 
using namespace std;
const int N=33;
const int INF=0x3f3f3f3f;
int num[N], res[N];
struct node{
    int data;
    node* lchild;
    node* rchild;
};
int n, idx=1;

node* findMin(int l, int r){
    int index, data=INF;
    if(l>r)
        return NULL;

    for(int i=l; i<=r; i++){
        if(data>num[i]){
            data=num[i];
            index=i;
        }
    }

    node* root = new node;
    root->data=data;
    root->lchild=findMin(l, index-1);
    root->rchild=findMin(index+1, r);

    return root;
}

void BFS(node* root){
    queue q;
    q.push(root);
    while(!q.empty()){
        node* top = q.front();
        q.pop();
        res[idx++]=top->data;
        if(top->lchild!=NULL)
            q.push(top->lchild);
        if(top->rchild!=NULL)
            q.push(top->rchild);
    } 
}

int main()
{
    scanf("%d", &n);
    for(int i=1; i<=n; i++){
        scanf("%d", &num[i]);
    }

    node* root = findMin(1, n);
    BFS(root);

    for(int i=1; i<=n; i++){
        printf("%d", res[i]);
        if(i!=n)
            printf(" ");
        else
            printf("n");
    }
    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/780409.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号