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
思路
一般想法是先建树,再层序遍历,但这题只给出了中序遍历。可以观察到,根节点永远是当前序列的最小值,然后划分左右子树递归建树即可
cpp代码
#include<iostream>
#include<queue>
#include<vector>
#include<unordered_map>
using namespace std;
const int N = 50;
unordered_map<int, int> l, r;
int pos[N];
int getmin(int l, int r) {
int k = l;
for (int i = l; i <= r; i++)
if (pos[i] < pos[k])k = i;
return k;
}
int build(int inl, int inr) {
int k = getmin(inl, inr);
int root = pos[k];
if (k > inl)l[root] = build(inl, k - 1);
if (k < inr)r[root] = build(k + 1, inr);
return root;
}
void bfs(int root) {
queue<int> q;
vector<int>vec;
q.push(root);
while (q.size()) {
auto t = q.front();
q.pop();
vec.push_back(t);
if (l.count(t))q.push(l[t]);
if (r.count(t))q.push(r[t]);
}
cout << vec[0];
for (int i = 1; i < vec.size(); i++)cout << " " << vec[i];
puts("");
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++)cin >> pos[i];
int root = build(0, n - 1);
bfs(root);
return 0;
}