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

A1167 Cartesian Tree(30分)PAT甲级 (Advanced Level) Practice(C++)满分题解【最小堆+构建树+层序遍历】

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

A1167 Cartesian Tree(30分)PAT甲级 (Advanced Level) Practice(C++)满分题解【最小堆+构建树+层序遍历】

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

 

代码如下:
#include
#include
#include
using namespace std;
const int MAX=0x3fffffff;
struct Node{
    int data;
    Node *left,*right;
}*tree;
vector nodelist;
Node* check(int low,int high)
{
    if(low<0||highdata=nodelist[min];
    newtree->left=check(low,min-1);
    newtree->right=check(min+1,high);
    return newtree;
}
int main()
{
    int n;
    cin>>n;
    for(int i=0;i>index;
        nodelist.push_back(index);
    }
    tree=check(0,n-1);
    int flag=0;
    queue q;
    q.push(tree);
    while(!q.empty()){
        Node *t=q.front();
        if(flag==1)cout<<" ";//只有第一个数前面不要输出空格
        else flag=1;
        cout<data;
        if(t->left)q.push(t->left);
        if(t->right)q.push(t->right);
        q.pop();
    }
    return 0;
}
运行结果如下:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/943056.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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