题目:笛卡尔树
笛卡尔树 是由一系列不同数字构成的二叉树。
树满足堆的性质,中序遍历返回原始序列。
最小笛卡尔树表示满足小根堆性质的笛卡尔树。
例如,给定序列 {8,15,3,4,1,5,12,10,18,6}{8,15,3,4,1,5,12,10,18,6},则生成的最小堆笛卡尔树如图所示。

现在,给定一个长度为 NN 的原始序列,请你生成最小堆笛卡尔树,并输出其层序遍历序列。
输入格式
第一行包含整数 NN。
第二行包含 NN 个两两不同的整数,表示原始序列。
输出格式
共一行,输出最小堆笛卡尔树的层序遍历序列。
数据范围
1≤N≤301≤N≤30,
原始序列中元素的取值范围 [−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
使用dsf递归算法构建树,bsf算法遍历输出树,bsf算法用到队列实现
DSF递归算法:
先在总序列中找到value值最小的元素作为整棵树的根节点,再递归调用dsf构造其左子树、右子树
BSF算法:
使用队列,先将根节点入队;输出根节点数据,出队,检索该结点左右子树是否为空,不为空则入队,依次检索,直到所有结点都检索完。
代码:
#include <iostream>
#include <queue>
using namespace std;
#define Max_int 2147483647
typedef struct Tree_Node{
int value;
struct Tree_Node *lchild,*rchild;
Tree_Node(int x) : value(x),lchild(NULL),rchild(NULL){}
}*BiTree;//笛卡尔树节点结构体
queue<BiTree>Tree;//BSF算法需用
int a[35],n;//原始序列 节点数
BiTree dfs(int l,int r) {
if (l > r) {
return NULL;
}
int min = Max_int;
int tag = 0;
for (int i = l; i <= r; i++) {
if (a[i] < min) {
min = a[i];
tag = i;
}
}//找出value最小的节点作为整棵树的根节点,然后进行递归
BiTree p = new Tree_Node(a[tag]);
p->lchild = dfs(l, tag - 1);
p->rchild = dfs(tag + 1, r);
return p;
}
void bfs(BiTree root){
while(!Tree.empty()){
BiTree p = (Tree.front());
Tree.pop();
cout<< p->value << " ";
if(p->lchild){
Tree.push(p->lchild);
}
if(p->rchild){
Tree.push(p->rchild);
}
}
}
int main() {
cin>> n;
for (int i = 0; i < n; i++) {
cin>> a[i];
}
BiTree root = dfs(0,n-1);
Tree.push(root);
bfs(root);
return 0;
}
1108

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



