7-4 Cartesian Tree (30分)

7-4 Cartesian Tree (30分)

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.

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

 

#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
int a[1009] ;
int find( int l ,int r ){
	int  minn= 9999999,idx=-1; 
	for( int i=l;i<=r;i++){
		 if( minn > a[i] ){
		     minn = a[i];
		     idx = i;
		 }
	}
	return idx;
}
struct NODE{
	int l ,r ;
}t;
int main(void){  
	int n;
	cin>>n;
	for( int i=1;i<=n;i++){ 
	     cin>>a[i];
    }
    queue<struct NODE> q;
    t.l = 1;
    t.r = n;
    int flag =0; 
    q.push( t );
	while( !q.empty() ){
    	   if( !flag )
    	      flag =1;
    	   else cout<<" ";
		   t = q.front();
		   q.pop();
		   int idx = find( t.l , t.r);
		   if( idx != -1 ){ 
		       cout<<a[idx];
			   int r = t.r;
			   if( idx-1 >= t.l){ 
			       t.r = idx-1;
			       q.push(t);   
			   }
			   if( idx+1 <= r){
			   	   t.l = idx+1;
			   	   t.r = r;
				   q.push( t );
			   }
			}
	}
 	return 0;
}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 程序猿惹谁了 设计师:白松林 返回首页