HDU

来源:互联网 发布:交通枢纽大数据 编辑:程序博客网 时间:2024/05/21 11:17

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
41 3 4 2
Sample Output
1 3 2 4


题意:构建二叉搜索树,输出按字典序最小的插入方式使得和构建的二叉搜索树一样;

思路:构建好二叉搜索树,直接输出前序遍历(要想插入和原图一样的话,只有先序遍历最小了,自己好好想想);

代码:

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;#define Max 100010int f;struct node{int tt;node *left;node *right;node(int k){tt = k;left = NULL;right = NULL;}};node *insert(node *root,int k) // 插入值,构建二叉搜索树; {if(root==NULL){node *pp = new node(k);return pp;}else{if(k<root->tt)root->left = insert(root->left,k);else root->right = insert(root->right,k);return root;}}void prodfs(node *root)   // 输出先序遍历; {if(root==NULL)return ;if(!f){printf("%d",root->tt);f=1;}else printf(" %d",root->tt);prodfs(root->left);prodfs(root->right);}int main(){int i,j,n;while(~scanf("%d",&n)){node *root=NULL;int k;f=0;for(i=0;i<n;i++){scanf("%d",&k);root = insert(root,k);}prodfs(root);printf("\n");}return 0;}



原创粉丝点击