Elven Postman(hdu5444)
题目链接hdu5444
从总根出发,如果比当前根值大往左继续查询且输出W,比当前根值小往右继续查询且输出E,在根就换行并且返回,且每一个快递都是从最顶部出发
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<set>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<string>
#include<algorithm>
#include<sstream>
#include<memory>
#include<functional>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a));
#define ll long long int
const int INF = 0x3f3f3f3f;
struct node
{
int val;//根
node *lch,*rch;//左和右
};
int flag;//flag用来标记
node *insert(node *root,int x)//插入
{
if(root==NULL)//如果该点未被填充
{
node *q=new node;//开辟空间
q->val=x;//填充根点
q->lch=q->rch=NULL;//左右子树设为空
return q;
}
//以下是根点填充后再次开辟空间//
if(x<root->val)//如果x小于根就放入左子树
root->lch=insert(root->lch,x);
else//x大于根反之
root->rch=insert(root->rch,x);
return root;
}
void find(node *p,int x)//查询
{
if(p==NULL) return;
else if(x==p->val) return;//如果在根上找到了值则什么都不输出
else if(x<p->val) {printf("E");find(p->lch,x);}//如果在左子树上找到了值则输出E
else if(x>p->val) {printf("W");find(p->rch,x);} //如果在右子树上找到了则输出W
}
int main()
{
int t,x,n,m,y;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
flag=1;//初始化标记
node *root=NULL;//开辟新顶根
for(int i=0;i<n;++i)
{
scanf("%d",&x);
root=insert(root,x);//插入
}
scanf("%d",&m);
while(m--)
{
scanf("%d",&y);
find(root,y);//查询函数
printf("\n");
}
}
return 0;
}