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
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
按照题目要求构建二叉树,再层次遍历即可
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int N = 31;
struct node{
int ele=-1;
int lchild=-1;
int rchild=-1;
} nodes[N];
int min_heap=-1;
int n;
int gol_root;
vector<int> level_order;
void search(int fa, int l, int r)
{
if(l>r) return;
int root=l;
for(int i=l+1 ; i<=r ; i++)
if(nodes[i].ele<nodes[root].ele)
root = i;
if(fa == -1) gol_root = root;
else if(nodes[fa].lchild == -1) nodes[fa].lchild=root;
else nodes[fa].rchild=root;
search(root, l, root-1);
search(root, root+1, r);
}
void level_tra(int root)
{
queue<int> q;
q.push(root);
while(!q.empty())
{
int x = q.front();
level_order.push_back(nodes[x].ele);
q.pop();
if(nodes[x].lchild!=-1) q.push(nodes[x].lchild);
if(nodes[x].rchild!=-1) q.push(nodes[x].rchild);
}
}
int main()
{
cin>>n;
for(int i=1 ; i<=n ; i++)
{
cin>>nodes[i].ele;
}
search(-1,1,n);
level_tra(gol_root);
for(int i=0 ; i<level_order.size()-1 ; i++)
cout<<level_order[i]<<" ";
cout<<level_order[level_order.size()-1];
return 0;
}