The order of a Tree HDU - 3999

The order of a Tree

  HDU - 3999 
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
 
 
 
 
代码:
#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");
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值