hdu5444(模拟)

题意:建树,给你几个点,要求输出走到各个点的路径(左为E,右为W,树的遍历)

二叉树的模拟题,但是GG了两次。
主要是没注意到直接模拟会爆掉- -,进行下处理就好了


#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

int tree[1100];
int ls[1100];
int rs[1100];
int nCount = 0;

void add(int root, int value)
{
    if(tree[root]==-1)
    {
        tree[root] = value;
    }
    else if(value>tree[root])
    {
        if(ls[root]!=-1)
        {
            add(ls[root], value);
        }
        else
        {
            ls[root] = ++nCount;
            add(ls[root], value);
        }
    }
    else
    {
        if(rs[root]!=-1)
        {
            add(rs[root], value);
        }
        else
        {
            rs[root] = ++nCount;
            add(rs[root], value);
        }
    }
}

void traver(int root, int value)
{
    if(tree[root]==value) return;
    else if(tree[root]<value)
    {
        printf("W");
        traver(ls[root], value);
    }
    else
    {
        printf("E");
        traver(rs[root], value);
    }

}

int main()
{
    int t, n, num, q, tt;
    scanf("%d", &t);
    while(t--)
    {
        nCount = 0;
        scanf("%d", &n);
        memset(tree, -1, sizeof(tree));
        memset(ls, -1, sizeof(ls));
        memset(rs, -1, sizeof(rs));
        for(int i=0; i<n; i++)
        {
            scanf("%d", &num);
            add(0, num);
        }
        scanf("%d", &q);
        for(int i=0; i<q; i++)
        {
            scanf("%d", &tt);
            traver(0, tt);
            printf("
");
        }
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/Przz/p/5409760.html