HDU5444-二叉树模拟-Elven Postman

http://acm.hdu.edu.cn/showproblem.php?pid=5444
用数组表示二叉树,明天写一个正常的

#include<stdio.h>
#include<string.h>
struct node {
    int l,r,val;
}tree[100005];
int tot=1;//tot用来赋值,用数组模拟二叉树
void init(int tot)
{
    tree[tot].l=tree[tot].r=0;
}
void insert1(int x,int val){
      if(tree[x].l&&tree[x].val>val) insert1(tree[x].l,val);
      else if(tree[x].r&&tree[x].val<val) insert1(tree[x].r,val);//可以递归,就递归几层
      else {init(tot);//创建一个节点
      tree[tot].val=val;//插入
      if(tree[x].val>val)
         tree[x].l=tot;//连接
      else tree[x].r=tot;
      tot++;}
}
void query(int x,int val){
    if(val==tree[x].val){printf("\n");return;}
    if(tree[x].val>val){             //如果当前值小于根,那么往左子树找
        printf("E");
        query(tree[x].l,val);
    }
    else {                            //往右子树找
        printf("W");
        query(tree[x].r,val);
    }


}
int main()
{
    int T,i,j,k,n,a[1005],b[1005],q,x;
    scanf("%d",&T);
    while(T--)
    {
         tot=1;
        scanf("%d",&n);
        for(i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            if(i==1){
                init(tot);
                tree[tot].val=a[i];
                tot++;
            }
            else insert1(1,a[i]);
        }
        scanf("%d",&q);
        while(q--)
        {
            scanf("%d",&x);
            query(1,x);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值