HDU The order of a Tree

来源:互联网 发布:linux usermod命令 编辑:程序博客网 时间:2024/05/28 15:07

原文链接 http://acm.hdu.edu.cn/showproblem.php?pid=3999

The order of a Tree

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1046    Accepted Submission(s): 553


Problem Description
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 <iostream>#include <cstdio>#include <cstdlib>using namespace std;bool first;typedef struct BiTNode{    int value;    struct BiTNode *lchild,*rchild;}*BiTree;bool Search(BiTree root){    if(root!=NULL&&first)    {        first = false;        printf("%d",root->value);        Search(root->lchild);        Search(root->rchild);    }    else if(root!=NULL)    {        printf(" %d",root->value);        Search(root->lchild);        Search(root->rchild);    }}void Built(BiTree &root,int data){    if(root == NULL)    {        root = (struct BiTNode *)malloc(sizeof(BiTNode));        root->value = data;        root->lchild = root->rchild = NULL;    }    else    {        if(data < root->value)        {            Built(root->lchild,data);        }        else        {          Built(root->rchild,data);        }     }}int main(){    int i,n;    int a[100001];    BiTree root;    while(scanf("%d",&n)!=EOF)    {        root = NULL;        first = true;        for(i = 1;i <= n;i++)        {            scanf("%d",&a[i]);            Built(root,a[i]);        }        Search(root);        printf("\n");    }    return 0;}



0 0
原创粉丝点击