PAT-2019年冬季考试-甲级 7-4 Cartesian Tree (30分)——小根堆的中序遍历求层序遍历

7-4 Cartesian Tree (30分)

A Cartesian tree is a binary tree constructed from a sequence of distinct numbers. The tree is heap-ordered, and an inorder traversal returns the original sequence. For example, given the sequence { 8, 15, 3, 4, 1, 5, 12, 10, 18, 6 }, the min-heap Cartesian tree is shown by the figure.
在这里插入图片描述
Your job is to output the level-order traversal sequence of the min-heap Cartesian tree.

Input Specification:
Each input file contains one test case. Each case starts from giving a positive integer N (≤30), and then N distinct numbers in the next line, separated by a space. All the numbers are in the range of int.

Output Specification:
For each test case, print in a line the level-order traversal sequence of the min-heap Cartesian tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the beginning or the end of the line.

Sample Input:

10
8 15 3 4 1 5 12 10 18 6

Sample Output:

1 3 5 8 4 6 15 10 12 18

题意:

7-4笛卡尔树(30分)

笛卡尔树是由一系列不同的数字构成的二叉树。树是按堆排序的,按顺序遍历返回原始序列。例如,给定序列{8、15、3、4、1、5、12、10、18、6},最小堆笛卡尔树如图所示。

在这里插入图片描述

您的工作是输出最小堆笛卡尔树的级别顺序遍历序列。

输入规格:

每个输入文件包含一个测试用例。每种情况从给出一个正整数N(≤30)开始,然后在下一行中给出N个不同的数字,用空格隔开。所有的数字都在整数范围内。

输出规格:

对于每个测试用例,一行打印最小堆笛卡尔树的级别顺序遍历序列。一行中的所有数字必须用一个空格隔开,并且行的开头或结尾不能有多余的空格。

思路:

利用最小堆的性质,根为当前子树最小的值,得到根的下标,而中序遍历为LNR,得到根下标即可分开左子树和右子树。
在这里插入图片描述

代码来源

#include<bits/stdc++.h>
using namespace std;
int a[505],b[505];
int n;
struct node{
    int d;
    node *left,*right;
};
queue<node*>q;
vector<int>v;
node* build(int l,int r){
    if(l>r) return NULL;
    node *root=new node();
    int pos=-1,k=9999999;//找到最小的 
    for(int i=l;i<=r;i++){
        if(k>a[i]){
            k=a[i];
            pos=i;
        }
    }
    root->d=a[pos];
    root->left=build(l,pos-1);//左子树 
    root->right=build(pos+1,r);//右子树 
    return root;
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    node *root=build(1,n);//建树 
    q.push(root);//bfs层序遍历 
    while(!q.empty()){
        node *tree=q.front();
        q.pop();
        v.push_back(tree->d);
        if(tree->left) q.push(tree->left);
        if(tree->right) q.push(tree->right);
    }
    for(int i=0;i<v.size();i++){//输出 
        cout<<v.at(i);
        if(i!=v.size()-1) cout<<" ";
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

隔壁de小刘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值