HDU_3999_二叉排序树

本文介绍了一种构建二叉搜索树的方法,并给出了一种算法用于寻找生成相同形状二叉树的最小字典序序列。通过递归插入节点的方式构建二叉树,再采用深度优先遍历输出节点,确保输出的序列能够生成与输入序列相同的二叉树。

The order of a Tree

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


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

 

Sample Output
1 3 2 4
 
给一个序列,依照序列建二叉排序树,输出建成这棵树的最小字典序列。
不能使用线段树那种表示方式来表示树,因为可能会退化为一条链,这时会溢出。
所以用lson和rson两个数组分别存每个结点的左右儿子(题中规定,数字为1—n)。
 
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

int lson[100005],rson[100005],n;

void Insert(int rt,int x)
{
    if(rt>x)
    {
        if(lson[rt]==0)
            lson[rt]=x;
        else
            Insert(lson[rt],x);
    }
    else
    {
        if(rson[rt]==0)
            rson[rt]=x;
        else
            Insert(rson[rt],x);
    }

}

int cnt=0;
void order(int rt)   //深搜
{
    if(rt==0)
        return;
    printf("%d",rt);
    cnt++;
    if(cnt==n)
        printf("\n");
    else
        printf(" ");
    order(lson[rt]);
    order(rson[rt]);
}

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        cnt=0;
        int num,root;
        memset(lson,0,sizeof(lson));
        memset(rson,0,sizeof(rson));
        scanf("%d",&root);
        for(int i=1; i<n; i++)
        {
            scanf("%d",&num);
            Insert(root,num);
        }
        order(root);
        //cout<<n<<" "<<cnt<<endl;
    }
    return 0;
}

 

 

转载于:https://www.cnblogs.com/jasonlixuetao/p/5705150.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值