当前位置:网站首页>笛卡尔树(暑假每日一题 9)
笛卡尔树(暑假每日一题 9)
2022-07-29 18:50:00 【sweetheart7-7】
笛卡尔树 是由一系列不同数字构成的二叉树。
树满足堆的性质,中序遍历返回原始序列。
最小笛卡尔树表示满足小根堆性质的笛卡尔树。
例如,给定序列 { 8 , 15 , 3 , 4 , 1 , 5 , 12 , 10 , 18 , 6 } \{8,15,3,4,1,5,12,10,18,6\} { 8,15,3,4,1,5,12,10,18,6},则生成的最小堆笛卡尔树如图所示。

现在,给定一个长度为 N N N 的原始序列,请你生成最小堆笛卡尔树,并输出其层序遍历序列。
输入格式
第一行包含整数 N N N。
第二行包含 N N N 个两两不同的整数,表示原始序列。
输出格式
共一行,输出最小堆笛卡尔树的层序遍历序列。
数据范围
1 ≤ N ≤ 30 , 1≤N≤30, 1≤N≤30,
原始序列中元素的取值范围 [ − 2147483648 , 2147483647 ] [−2147483648,2147483647] [−2147483648,2147483647]。
输入样例:
10
8 15 3 4 1 5 12 10 18 6
输出样例:
1 3 5 8 4 6 15 10 12 18
- 根据小根堆的性质,当前子树的根节点是当前区间元素中最小的,且中序遍历结果为原序列可以得出,根节点左边的元素是当前节点的左子树,右边的元素是当前节点的右子树。
- 递归实际上是一种前序遍历,所以可以将当前元素加入 层数为 d 的数组中,然后再依次遍历每层的数组,遍历结果为层序遍历结果。
不用 bfs
#include<iostream>
#include<vector>
using namespace std;
const int N = 40;
int n;
int w[N];
vector<int> level[N];
int getmin(int l, int r){
int res = l;
for(int i = l; i <= r; i++)
if(w[res] > w[i]) res = i;
return res;
}
void dfs(int l, int r, int d){
if(l > r) return;
int root = getmin(l, r);
level[d].push_back(w[root]);
dfs(l, root - 1, d + 1);
dfs(root + 1, r, d + 1);
}
int main(){
cin >> n;
for(int i = 0; i < n; i++)
cin >> w[i];
dfs(0, n - 1, 0);
for(int i = 0; level[i].size(); i++)
for(int j = 0; j < level[i].size(); j++)
cout << level[i][j] << ' ';
return 0;
}
用bfs
#include<iostream>
#include<vector>
using namespace std;
const int N = 40;
int n;
int q[N];
int w[N], L[N], R[N];
vector<int> level[N];
int getmin(int l, int r){
int res = l;
for(int i = l; i <= r; i++)
if(w[res] > w[i]) res = i;
return res;
}
int dfs(int l, int r){
if(l > r) return -1;
int root = getmin(l, r);
L[root] = dfs(l, root - 1);
R[root] = dfs(root + 1, r);
return root;
}
void bfs(int root){
int hh = 0, tt = 0;
q[0] = root;
while(hh <= tt){
int u = q[hh ++];
if(L[u] != -1) q[++tt] = L[u];
if(R[u] != -1) q[++tt] = R[u];
}
for(int i = 0; i <= tt; i++)
cout << w[q[i]] << ' ';
}
int main(){
cin >> n;
for(int i = 0; i < n; i++)
cin >> w[i];
int root = dfs(0, n - 1);
bfs(root);
return 0;
}
边栏推荐
猜你喜欢
随机推荐
如何防止订单重复支付?
答对这3个面试问题,薪资直涨20K
R语言ggplot2可视化绘制条形图(bar plot)、使用gghighlight包突出高亮条形图中的特定条形(highlight specific bar plot)
洪九果品、百果园抢滩港股,卖水果是门好生意吗?
Mobile Banking Experience Test: How to Get the Real User Experience
Android 面试黑洞——当我按下 Home 键再切回来,会发生什么?
Answer these 3 interview questions correctly, and the salary will go up by 20K
算力顶天地,存力纳乾坤:国家超级计算济南中心的一体两面
Apache Doris 1.1 特性揭秘:Flink 实时写入如何兼顾高吞吐和低延时
FPGA设计8位异步、同步二进制计数器
【APP 改进建议】希望增加 pdf 及 word 的导出能力
R语言时间序列数据提取:使用xts包的last函数提取时间序列中最后面10天的数据(last 10 day)
MySQL 中的反斜杠 \\,真是太坑了
【PyCharm 常用快捷键】
软件测试面试屡屡失败,面试官总是说逻辑思维混乱,怎么办?
第02章 MySQL的数据目录【1.MySQL架构篇】【MySQL高级】
R语言使用treemap包中的treemap函数可视化treemap图:treemap将分层数据显示为一组嵌套矩形,每一组都用一个矩形表示,该矩形的面积与其值成正比
高速无源链路阻抗匹配套路
7行代码让B站崩溃3小时,竟因“一个诡计多端的0”
Test basis: Redis of Nosql database








