(二叉树创建+查找)精灵邮差

题目

精灵是非常奇特的生物。众所周知,他们可以活很长时间,他们神奇的能力不是一件容易接受的事情。此外,他们住在树上。但是,你可能不知道有些事情。虽然通过魔法传送提供东西非常方便(很像电子邮件)。他们有时仍然喜欢其他更“传统”的方法。

因此,作为一名精灵邮递员,了解如何将邮件传递到树的正确房间至关重要。精灵树在交叉时总是分成不超过两条路径,无论是东方向还是西方。巧合地看起来非常像人类计算机科学家所知的二叉树。不仅如此,在为房间编号时,他们总是将房间编号从最东边的位置编号到西边。东部的房间通常更优选,更昂贵,因为他们有幸看到日出,这在精灵文化中很重要。

无论如何,精灵们通常会在树的根部按顺序记下所有房间,以便邮递员知道如何发送邮件。序列如下,它将直接访问最东边的房间并记下沿途遇到的每个房间。到达第一个房间后,它将进入下一个未访问过的最东边的房间,在路上写下每个未访问的房间,直到所有房间都被访问。

您的任务是根据写在根上的顺序确定如何到达某个房间。

例如,序列2,1,4,3将写在下一棵树的根上。
Input
First you are given an integer T(T≤10) indicating the number of test cases.

For each test case, there is a number n(n≤1000) on a line representing the number of rooms in this tree. n integers representing the sequence written at the root follow, respectively a1,…,an where a1,…,an∈{1,…,n}.

On the next line, there is a number q representing the number of mails to be sent. After that, there will be q integers x1,…,xq indicating the destination room number of each mail.
Output
For each query, output a sequence of move (E or W) the postman needs to make to deliver the mail. For that E means that the postman should move up the eastern branch and W the western one. If the destination is on the root, just output a blank line would suffice.

Note that for simplicity, we assume the postman always starts from the root regardless of the room he had just visited.
Sample Input
2
4
2 1 4 3
3
1 2 3
6
6 5 4 3 2 1
1
1
Sample Output
E

WE
EEEEE

分析与解答

1.由于输入是先根,然后小的在e,大的在w按,按根左右建树
左右根据数和根的大小判断,大的我们建右子树,小的左
《(二叉树创建+查找)精灵邮差》
《(二叉树创建+查找)精灵邮差》
利用每个子结点都可看作是树根来建
2.查找的时候,x小与根的值,输出e,向左子树继续找,找到就返回

#include<cstdio>
#include<algorithm>
using namespace std;
struct node {
    int v;
    node *left,*right;
}; 
node * insert(node *p,int x)
{
    if(p==NULL){
        node * q=new node;
        q->v=x;
        q->left=NULL;
        q->right=NULL;
        return q;
    }
    else{
        if(x<p->v) p->left=insert(p->left,x);
        else p->right=insert(p->right,x);
        return p;
    }
}
void find (node *p,int x){
    if(p==NULL) return ;
    else if(x==p->v) return;
    else if(x<p->v) {
        printf("E");
        find(p->left,x);
    }
    else if(x>p->v){
        printf("W");
        find(p->right,x);
    }
}
void remove (node *p){
    if(p==NULL) return;
    remove(p->left);
    remove(p->right);
    free(p);
}

int main(){
    int t,n,m,x,y;
    scanf("%d",&t);
    while(t--){
        node *root =NULL;
        remove(root);
        scanf("%d",&n);
        for(int i=0;i<n;++i){
            scanf("%d",&x);
            root = insert(root,x);
        } 
        scanf("%d",&m);
        for(int i=0;i<m;++i){
            scanf("%d",&y);
            find(root,y);
            printf("\n");
        }
    }
}


    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/qq_40828914/article/details/81407537
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞