1167 Cartesian Tree

文章介绍了如何从给定的数字序列构建最小堆卡特兰树,并提供了C++代码实现,通过层序遍历输出树的序列。
摘要由CSDN通过智能技术生成

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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值