1167 Cartesian Tree (30 分)

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

 分析:

建树:1.通过输入序列找到左侧到右侧最小数及其下标;2.查找左侧到下标之间的最小数、下标到右侧之间的最小数进行插入;3.重复上述步骤;

max_element()与min_element()分别用来求最大元素和最小元素的位置

接收参数:容器的首尾地址(迭代器)(可以是一个区间)

返回:最值元素的地址(迭代器),需要减去序列头以转换为下标

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<cmath>
#include<unordered_map>
//1009;
using namespace std;
typedef long long ll;
const int inf = 99999999;
int n;
string s,t;
struct tree {
	int key;
	tree *left;
	tree *right;
};
int a[35];
tree* create(int left,int right) {
	if (left > right) return NULL;
	int index = min_element(a + left, a + right + 1)-a; //获取left-right最小数的下标
	tree* root = new(tree);
	root->key = a[index];
	root->left = create(left, index - 1);
	root->right = create(index + 1, right);
	return root;
}
int main() {
	tree *root = NULL;
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}
	root = create(0,n-1); //建树
	queue<tree*> q; //构建队列对数进行层遍历
	q.push(root);
	int cnt = 0;
	while (!q.empty()) {
		if (cnt++) cout << " ";
		tree *tmp = q.front();
		cout << tmp->key;
		q.pop();
		if (tmp->left) q.push(tmp->left);
		if (tmp->right) q.push(tmp->right);
	}
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值