PAT 1167 Cartesian Tree

个人学习记录,代码难免不尽人意。

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.
PAT 1167 Cartesian Tree_第1张图片
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 
#include
#include
#include
#include
#include 
#include
using namespace std;
const int maxn=40;
const int INF=1000000000;
struct node{
	int data;
	node* lchild;
	node* rchild;
}; 
node* newnode(int data){
	node* root=new node;
	root->data=data;
	root->lchild=NULL;
	root->rchild=NULL;
	return root;
}
int in[maxn];
node* create(int inl,int inr){
	if(inl>inr) return NULL;
	int min=INF;
	int index;
	for(int i=inl;i<=inr;i++){
		if(in[i]<min){
			min=in[i];
			index=i;
		}
	}
	node* root=newnode(min);
	root->lchild=create(inl,index-1);
	root->rchild=create(index+1,inr);
	return root;
}
void bfs(node* root,int n){
	queue<node*> q;
	q.push(root);
	int cnt=0;
	while(!q.empty()){
		node* now=q.front();
		q.pop();
		printf("%d",now->data);
		cnt++;
		if(cnt!=n) printf(" ");
		else printf("\n");
		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++){
    	scanf("%d",&in[i]);
	}
	node* root=create(0,n-1);
	bfs(root,n);
}

这道题简单的出乎我的意料了,就是最简单的建树+bfs遍历,出在最后一题有些反套路了,这也提醒我们一道题不要耗太多时间,后面说不定有送分题。因为前面三道都记录了,这道题我也记录一下吧。O(∩_∩)O哈哈~

你可能感兴趣的:(PTA,算法,c++,pat,数据结构)