7-4 Cartesian Tree (30分)

82 篇文章 0 订阅
11 篇文章 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

题解:递归处理左右子树,然后层序输出即可。

#include <bits/stdc++.h>
using namespace std;
const int N = 35;
int n;
int arr[N], res[N];
vector< vector<int> > G;
void dfs(int l, int r, int k){
	if(l > r) return;
	if(l == r) {
		G[k].push_back(arr[r]);
		return;
	}
	int t = l;
	for(int i = l; i <= r; i++){
		if(arr[t] > arr[i]) t = i;
	}
	G[k].push_back(arr[t]);
	dfs(l,t-1, k+1);
	dfs(t+1, r, k+1);
}
int main(){
	scanf("%d", &n);
	G.resize(n+1);
	for(int i = 0; i < n; i++) {
		scanf("%d", &arr[i]);
	}
	dfs(0, n-1, 0);
	bool flag = false;
	for(int i = 0; i <= n; i++){
		for(int j = 0; j < G[i].size(); j++){
			if(!flag){
				printf("%d", G[i][j]);
				flag = true;
			}else printf(" %d", G[i][j]);
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值