原题链接:暂无
参考的浒鱼鱼的博客:19年冬季第四题 PAT甲级 1167 Cartesian Tree (30分)超级详解不AC都难
关键词:堆的性质、建树、BFS
整理时间:2020.7.23
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
题目大意: 给出二叉最小堆的中序遍历序列,输出层序遍历结果。
思路: 小根堆的性质:根为当前子树最小的值,得到根下标即可在中序遍历中分开左子树和右子树。建树完成后用bfs遍历输出即可。
代码:
#include<bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f;
const int maxn = 210;
vector<int> in;
struct node{
int data;
node* lchild, *rchild;
node(int x){ //生成结点
data = x; lchild = rchild = NULL;
}
};
int find_min(int L,int R){ //在最小堆中,根为当前子树最小的值
int Min = INF, index = -1;
for(int i = L; i <= R; i++){
if(in[i] < Min){
Min = in[i];
index = i;
}
}
return index; //返回根在中序遍历的位置
}
node* build(int L,int R){ //建树
if(L > R) return NULL;
int X = find_min(L,R);
node* root = new node(in[X]);
root->lchild = build(L,X-1);
root->rchild = build(X+1,R);
return root;
}
int cnt = 0,n;
void BFS(node* root){ //bfs遍历树输出层序遍历
queue<node*> q;
q.push(root);
while(!q.empty()){
node* now = q.front();
q.pop();
printf("%d",now->data);
cnt++;
if(cnt != n) printf(" "); //格式控制
else printf("\n");
if(now->lchild)
q.push(now->lchild);
if(now->rchild)
q.push(now->rchild);
}
}
int main(){
scanf("%d",&n); //结点数
in.resize(n);
for(int i = 0; i < n; i++)
scanf("%d",&in[i]);
node* root = build(0,n-1);
BFS(root);
return 0;
}