2019.12.7PAT冬季考试第四题 - 7-4 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.

CTree.jpg

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

 Catesian树,其实很简单,已知树是堆排序的,同时给出树的中序遍历结果,还原这个树。

这道题应该是做过的,比如给出前序和中序,还原树。但是考试的时候自己脑子太乱了,总觉得有思路,但是什么都没有写出来,还差一丢丢能力。在建树的过程中和思路方面都有欠缺。 

1.自己的代码

很遗憾,自己并没有有效的提交数据。

2.大神的代码

给出了一个堆树的中序,那么只要找到根节点(根节点就是最小值),直接分割左右子树,递归查找即可!

直接建树!建树的过程和建BST树是很像的,只不过每次要找根节点,根节点其实就是范围内的最小值,一个个遍历寻找就好了。

#include <cstdio>
#include <vector>
#include <algorithm>
#include <set>
#include <queue>
using namespace std;
struct Node{
	int data;
	Node *lchild, *rchild;
};
int in[50];
int minData(int l, int r){
	int minNum=1000000000;
	for (int i=l; i<=r; i++){
		if (in[i]<minNum){
			minNum=in[i];
		}
	}
	return minNum;
}
Node *create(int left, int right){
	if (left>right){
		return NULL;
	}
	Node *root=new Node;
	root->lchild=root->rchild=NULL;
	int minNum=minData(left, right);
	root->data=minNum;
//	printf("%d ",minNum);
	int k; 
	for (k=left; k<=right; k++){
		if (in[k]==minNum){
			break;
		}
	}
	root->lchild=create(left, k-1);
	root->rchild=create(k+1, right);
	return root;
}
void BFS(Node *root){
	queue<Node *> q;
	q.push(root);
	int cnt=0;
	while (!q.empty()){
		Node *now=q.front();
		q.pop();
		if (cnt++) printf(" ");
		printf("%d",now->data);
		if (now->lchild!=NULL) q.push(now->lchild);
		if (now->rchild!=NULL) q.push(now->rchild);
	}
}
int main(){
	int n;
	scanf("%d",&n);
	for (int i=0; i<n; i++){
//		int data;
		scanf("%d", &in[i]);
		
	}
	Node *root=NULL;
	root=create(0,n-1);
	BFS(root);
	return 0;
}

3.总结 

问题有2.

1.BST建树流程把握不熟。

2.建树过程,根的要求只有一个,最小值,按顺序遍历就好了(就用最傻的方法!),先完成再说,不考虑时间复杂度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值