HDU 5444 Elven Postman

来源:互联网 发布:java入门到精通4 pdf 编辑:程序博客网 时间:2024/06/05 02:53

题目分析

就是一个暴力建树,还有一个暴力查询的题。不过要知道怎么建还只要找规律的,大家可以发现,如果
给定一个数值如果比根的值小,那么往根的左边走,不是则往右边走。(当然如果根没有值,直接将该数值填到根结点就可以了)。同理,往左后者往右的时候如果该部分为空,直接将该值填进去即可。同时每次执行完都要删除这个数,并且把根设置为空。

#include <cstdio>#include <cstring>#include <iostream>#include <cstdlib>using namespace std;struct BTNode{    int data;    struct BTNode *left,*right;};BTNode *root;void build(int x){    BTNode *temp = (BTNode *)malloc(sizeof(BTNode));    temp->data = x;    temp->left = temp->right = NULL;    if(root == NULL)        root = temp;    else    {        BTNode *pre;        BTNode *cur = root;        while(cur != NULL)        {            pre = cur;            if(cur->data > x)                cur = cur->left;            else                cur = cur->right;        }        if(pre->data > x)            pre->left = temp;        else            pre->right = temp;    }}void query(int x){    BTNode *temp = root;    while(temp->data != x)    {        if(temp->data > x)        {            printf("E");            temp = temp->left;        }        else        {            printf("W");            temp = temp->right;        }    }}void Delete(BTNode *temp){    if(temp != NULL)    {        Delete(temp->left);        Delete(temp->right);        free(temp);    }}int main(){    int T;    scanf("%d", &T);    while(T--)    {        root = NULL;        int n,q,x;        scanf("%d", &n);        while(n--)        {            scanf("%d", &x);            build(x);        }        scanf("%d", &q);        while(q--)        {            scanf("%d", &x);            query(x);            printf("\n");        }        Delete(root);    }    return 0;}
0 0
原创粉丝点击