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 <algorithm>
#include <queue>
using namespace std;
struct node {
int val;
node *left;
node *right;
} *tree;
int n, cnt;
int a[50], b[50];
queue<node *>q;
node *build(int t, int l, int r) {
if (l > r) {
return NULL;
}
node *root = new node();
root->val = a[t];
int minn = (1 << 31) - 1;
int ind;
for (int i = l; i < t; i++) {
if (minn > a[i]) {
minn = a[i];
ind = i;
}
}
root->left = build(ind, l, t - 1);
minn = (1 << 31) - 1;
for (int i = t + 1; i <= r; i++) {
if (minn > a[i]) {
minn = a[i];
ind = i;
}
}
root->right = build(ind, t + 1, r);
return root;
}
int main() {
cin >> n;
int minn = (1 << 31) - 1;
int ind;
for (int i = 0; i < n; i++) {
cin >> a[i];
if (minn > a[i]) {
minn = a[i];
ind = i;
}
}
tree = NULL;
tree = build(ind, 0, n - 1);
q.push(tree);
while (!q.empty()) {
node *p = q.front();
q.pop();
b[cnt++] = p->val;
if (p->left != NULL) {
q.push(p->left);
}
if (p->right != NULL) {
q.push(p->right);
}
}
for (int i = 0; i < cnt; i++) {
cout << b[i];
if (i != cnt - 1) {
cout << ' ';
}
}
return 0;
}