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<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct node{
int v,lc,rc,level;
}a[1000];
int pos[10000]={0},maxlevel=0;
vector<int > v[100];
void cartesian(int index,int inl,int inr,int lev){
if(inl>inr) return ;
int m1=9999,m2=9999;
a[index].level=lev;
maxlevel=max(maxlevel,lev);
v[lev].push_back(index);
for(int i=inl;i<index;i++){
m1=min(m1,a[i].v);
}
a[index].lc=pos[m1];
cartesian(pos[m1],inl,index-1,lev+1);
for(int i=index+1;i<=inr;i++){
m2=min(m2,a[i].v);
}
a[index].rc=pos[m2];
cartesian(pos[m2],index+1,inr,lev+1);
}
int main(){
int n,small=99999;
cin>>n;
pos[9999]=-1;
for(int i=1;i<=n;i++){
int temp;
cin>>temp;
a[i].v=temp;
pos[temp]=i;
small=min(small,temp);
}
cartesian(pos[small],1,n,0);
for(int i=0;i<=maxlevel;i++){
for(int j=0;j<v[i].size();j++){
if(i==0&&j==0) cout<<a[v[i][j]].v;
else cout<<" "<<a[v[i][j]].v;
}
}
return 0;
}