The order of a Tree HDU

来源:互联网 发布:sql增加数据 编辑:程序博客网 时间:2024/05/28 18:42

The order of a Tree

 HDU - 3999 
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;typedef struct nodetree{    struct nodetree *l,*r;//左右孩子节点    int key;//父亲节点} tree;tree *root;int b[110000],a[110000];int c,n;tree *creat(int x)//通过申请空间建立临时指针指向父亲节点{    //动态申请一个空间,用来存放一个节点,并用临时指针t指向这个节点    tree *t=(tree *)malloc(sizeof(tree));    t->l=NULL;//把当前节点的左右孩子节点为空    t->r=NULL;    t->key=x;    return t;}tree *insert(tree *s,int x){    tree *t;    if(s==NULL)    {        t=creat(x);//调用creat函数创建父亲节点        s=t;        //printf("*****\n");    }    else//递归调用自己创建左右子树    {        if(x>s->key)//按照左小右大规则建立二叉树        {            s->r=insert(s->r,x);        }        else            s->l=insert(s->l,x);    }    return s;}void find(tree *root)//先序遍历{    if(root!=NULL)    {        if(c<n)        {            printf("%d ",root->key);            c++;        }        else            printf("%d\n",root->key);        find(root->l);//先序遍历左子树        find(root->r);//先序遍历右子树    }}int main(){    while(~scanf("%d",&n))    {        int str[110000];        int len,i;        root=NULL;        for(i=0;i<n;i++)            scanf("%d",&str[i]);        for(i=0; i<n; i++)        {            int num=str[i];            root=insert(root,num);//调用insert函数把各个节点插入树中            //root的值改变        }        c=1;        find(root);        //printf("\n");    }}


原创粉丝点击