7-4 Cartesian Tree (30 分)
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
最小堆中每一棵子树的根节点都是整棵子树的最小节点,根据中序序列找到遍历序列中最小节点的索引然后建树,然后用queue遍历就行
#include<bits/stdc++.h>
using namespace std;
struct Node {
int l = -1, r = -1;
};
vector<int> in;
vector<Node> Tree(40);
int bfs(int inL, int inR) {
if (inL > inR) return -1;
int Min = in[inL], V = inL;
for (int i = inL + 1; i <= inR; i++) {
if (in[i] < Min) {
Min = in[i];
V = i;
}
}
Tree[V].l = bfs(inL, V - 1);
Tree[V].r = bfs(V + 1, inR);
return V;
}
int main() {
int N;
scanf("%d", &N);
in.resize(N + 1);
Tree.resize(N + 1);
for (int i = 1; i<= N; i++){
scanf("%d", &in[i]);
}
int root = bfs(1, N), flag = 0;
queue<int> Q;
Q.push(root);
while(!Q.empty()) {
int temp = Q.front();
Q.pop();
if (flag == 0) {
flag = 1;
} else printf(" ");
printf("%d", in[temp]);
if (Tree[temp].l != -1) Q.push(Tree[temp].l);
if (Tree[temp].r != -1) Q.push(Tree[temp].r);
}
return 0;
}

本文介绍如何根据一组不重复的数字序列构建最小堆Cartesian树,并实现该树的层级遍历。通过寻找序列中的最小值建立树结构,再利用队列完成遍历过程。
325

被折叠的 条评论
为什么被折叠?



