2015长春Online:http://acm.hdu.edu.cn/showproblem.php?pid=5444
建一个二叉树,插入多个点,每次从根节点开始插入,如果当前节点为空则插入当前节点,否则如果小于当前节点的值,则插入右节点,否则插入左节点。
遍历的时候也如此,若找左儿子则输出W,找右儿子输出E,根节点输出空行。
#include <stdio.h>
struct tree
{
tree *lchild;
tree *rchild;
int key;
//tree(){}
tree(int x){
key = x;
lchild = rchild = NULL;
}
};
int q[1005];
void build(tree *root, int key)
{
if(root->key < key)
{
if(root->lchild == NULL){
root->lchild = new tree(key);
return;
}else build(root->lchild, key);
}
else
{
if(root->rchild == NULL){
root->rchild = new tree(key);
return;
}else build(root->rchild, key);
}
}
void getPath(tree *root, int target)
{
if(root->key == target){
puts("");
return;
}
else if(root->key > target){
printf("E");
getPath(root->rchild, target);
}else{
printf("W");
getPath(root->lchild, target);
}
}
int main()
{
int t, n, i, x, k;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
scanf("%d", &x);
tree *root = new tree(x);
for(i = 1;i < n;i++)
{
scanf("%d", &x);
build(root, x);
}
scanf("%d", &k);
for(i = 0;i < k;i++) scanf("%d", &q[i]);
for(i = 0;i < k;i++) getPath(root, q[i]);
}
}