这道题柳婼的解法太简洁了,把层序遍历这一步直接省略了,很厉害。index << 1 | 1 这个写法也很有趣,学习学习
https://liuchuo.blog.csdn.net/article/details/126225290
#include <cstdio>
#include <vector>
int N, root, pivot;
std::vector<int> vec, left, right, ans;
int cartesian(int begin, int end){
int r = vec[begin];
int loc = begin;
for(int i = begin; i < end; ++i){
if(vec[i] < r){
r = vec[i];
loc = i;
}
}
if(loc == begin){
left[loc] = -1;
} else{
left[loc] = cartesian(begin, loc);
}
if(loc == end - 1){
right[loc] = -1;
} else{
right[loc] = cartesian(loc + 1, end);
}
return loc;
}
int main(){
scanf("%d", &N);
vec.resize(N);
left.resize(N);
right.resize(N);
for(int i = 0; i < N; ++i){
scanf("%d", &vec[i]);
}
root = cartesian(0, N);
ans.push_back(root);
pivot = 0;
while(pivot < N){
if(left[ans[pivot]] != -1){
ans.push_back(left[ans[pivot]]);
}
if(right[ans[pivot]] != -1){
ans.push_back(right[ans[pivot]]);
}
++pivot;
}
for(int i = 0; i < N; ++i){
printf("%d", vec[ans[i]]);
if(i != N - 1){
printf(" ");
}
}
return 0;
}
题目如下:
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