hdu 3999 The order of a Tree(二叉搜索树)

在做另一道题的时候需要用到二叉搜索树,不过我不了解这种数据结构,所以学习一下。

这道题的话就是建立一个二叉搜索树,然后先序输出。

数组建树:

#include<stdio.h>
#include<string.h>
#define N 100005
struct node
{
    int x;
    int lson,rson;
} a[N*2];
int cnt;
int InsertTree(int t,int x)
{
    if(t==0)
    {
        t=cnt++;
        a[t].lson=0;
        a[t].rson=0;
        a[t].x=x;
    }
    else
    {
        if(x>a[t].x)
            a[t].rson=InsertTree(a[t].rson,x);
        else
            a[t].lson=InsertTree(a[t].lson,x);
    }
    return t;
}
void print(int t)
{
    if(t!=0)
    {
        printf(" %d",a[t].x);
        print(a[t].lson);
        print(a[t].rson);
    }
    return ;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        int i,t;
        scanf("%d",&t);
        a[1].x=t;
        a[1].lson=0;
        a[1].rson=0;
        cnt=2;
        for(i=2; i<=n; i++)
        {
            scanf("%d",&t);
            InsertTree(1,t);
        }
        printf("%d",a[1].x);
        print(a[1].lson);
        print(a[1].rson);
        printf("\n");
    }
    return 0;
}

链表建树:

#include<stdio.h>
#include<string.h>
#include<malloc.h>
struct node
{
    int x;
    node *lson,*rson;
}*root;
node *InsertTree(node *root,int x)
{
    if(root==NULL)
    {
        root=(node *)malloc(sizeof(node));
        root->lson=NULL;
        root->rson=NULL;
        root->x=x;
    }
    else
    {
        if(root->x>x) root->lson=InsertTree(root->lson,x);
        else root->rson=InsertTree(root->rson,x);
    }
    return root;
}
void print(node *root)
{
    if(root!=NULL)
    {
        printf(" %d",root->x);
        print(root->lson);
        print(root->rson);
    }
    return ;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        int i,x;
        root=NULL;
        for(i=1; i<=n; i++)
        {
            scanf("%d",&x);
            root=InsertTree(root,x);
        }
        printf("%d",root->x);
        print(root->lson);
        print(root->rson);
        printf("\n");
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值