The order of a Tree (二叉搜尋樹+先序遍歷)

韓小妹發表於2018-08-07

As we know,the shape of a binary search tree is greatly related to the order of keys we insert. To be precisely: 
1.  insert a key k to a empty tree, then the tree become a tree with 
only one node; 
2.  insert a key k to a nonempty tree, if k is less than the root ,insert 
it to the left sub-tree;else insert k to the right sub-tree. 
We call the order of keys we insert “the order of a tree”,your task is,given a oder of a tree, find the order of a tree with the least lexicographic order that generate the same tree.Two trees are the same if and only if they have the same shape. 

Input

There are multiple test cases in an input file. The first line of each testcase is an integer n(n <= 100,000),represent the number of nodes.The second line has n intergers,k1 to kn,represent the order of a tree.To make if more simple, k1 to kn is a sequence of 1 to n. 

Output

One line with n intergers, which are the order of a tree that generate the same tree with the least lexicographic. 

Sample Input

4
1 3 4 2

Sample Output

1 3 2 4

題意:題意給出一個序列,構造一棵二叉搜尋樹,讓你找一個序列,滿足:能構成與給出的序列相同的二叉搜尋樹,同時,字典序最小。

分析:首先構造二叉搜尋樹,然後先序遍歷輸出即可。

AC程式碼:

#include <stdio.h> 

typedef struct binTreeNode{
	int data;
	struct binTreeNode *lchild,*rchild;
} *BT;

void add( BT &T , int val ){//構造一個線索二叉樹 
	if( T==NULL ){
		T = new binTreeNode();
		T->data = val;
		T->lchild = T->rchild = NULL;
	} else if( T->data > val ){
		add( T->lchild,val );
	} else{ 
		add( T->rchild,val );
	} 
}

void preOrder( BT T , bool flag ){//先序輸出 
	if( T==NULL )
		return;
	else {
		if( !flag )
			printf( " " );
		printf( "%d",T->data );
		preOrder( T->lchild , 0);
		preOrder( T->rchild , 0);
	}
}

int main(){
	BT T;
	int n,v;
	while( ~scanf( "%d",&n ) ){
		T = NULL;
		for( int i=0 ; i<n ; i++ ){
			scanf( "%d",&v );
			add( T,v );
		}
		preOrder( T , 1 );
		printf( "\n" );
	}
}

 

相關文章