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
这是我在考场上ac的代码:
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <algorithm>
#include <set>
#include <queue>
using namespace std;
const int maxn = 100010;
struct node
{
int val=0;
node *lkid=nullptr, *rkid=nullptr;
};
int n;
int in[40];
node* creat(int left, int right) {
if (left > right) return nullptr;
int index = min_element(in + left, in + right + 1) - in;
node* tmp = new node;
tmp->val = in[index];
tmp->lkid = creat(left, index - 1);
tmp->rkid = creat(index + 1, right);
return tmp;
}
void level(node* root) {
queue<node*> q;
q.push(root);
bool flag = true;
while (!q.empty())
{
node* tmp = q.front();
q.pop();
if (flag) flag = false;
else printf(" ");
printf("%d", tmp->val);
if (tmp->lkid) q.push(tmp->lkid);
if (tmp->rkid) q.push(tmp->rkid);
}
}
int main() {
//freopen("test.txt", "r", stdin);
cin >> n;
//in.resize(n);
for (int i = 0; i < n; ++i) {
cin >> in[i];
}
node *root = new node;
root = creat(0, n - 1);
level(root);
return 0;
}