HDU 5444 - Elven Postman ( 二叉搜索树 )

题意

一些精灵住在一棵二叉搜索树上(???),给出一个序列表示这棵二叉搜索树(输入n个数的第一个数为根节点,第二个数和这个根节点比较大小,假如大于当前根节点的值,就往右边的节点走,小于往左边的节点走),现在邮递员要给他们送信,求送信每次走的方向。

思路

题目太长了 其实看懂了题意就能知道是个裸的二叉搜索树模板

AC代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;

struct node{
    int val;
    node *lch, *rch;
};

node *insert(node *p, int x){
    if(p==NULL){
        node *q = new node;
        q->val = x;
        q->lch = q->rch = NULL;
        return q;
    }
    else {
        if(x < p->val) p->lch = insert(p->lch, x);
        else p->rch = insert(p->rch, x);
        return p;
    }
}

void find(node *p, int x){
    if(p==NULL) return;
    else if(x==p->val) return;
    else if(x<p->val){
        printf("E");
        return find(p->lch, x);
    }
    else{
        printf("W");
        return find(p->rch, x);
    }
}

int main()
{
    int T, q, qq, d, n;
    scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        node *root = NULL;
        for(int i = 0; i < n; i++){
            scanf("%d",&d);
            root = insert(root, d);
        }
        scanf("%d",&q);
        while(q--){
            scanf("%d",&qq);
            find(root, qq);
            printf("\n");
        }
    }

    return 0;
}
posted @ 2018-08-17 10:05  JinxiSui  阅读(108)  评论(0编辑  收藏  举报