题意:
给出一颗二叉树的先序遍历,默认的中序遍历是1、2……n。给出q个询问,询问从根节点出发到某个点的路径。
解析:
就是构建一棵二叉搜索树,然后在二叉搜索树上面查找要查询的值,并输出路径。
my code
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxnode = (int)1e3+10;
int n;
struct Node {
int val, ch[2];
Node() {
val = 0;
memset(ch, 0, sizeof(ch));
}
Node(int val) {
this->val = val;
memset(ch, 0, sizeof(ch));
}
};
struct Tree {
int sz;
Node node[maxnode];
void clear() { sz = 0; }
int newNode(int val) {
node[++sz] = Node(val);
return sz;
}
void insert(int &u, int val) {
if(u == 0) {
u = newNode(val);
return ;
}
if(node[u].val > val) insert(node[u].ch[0], val);
else insert(node[u].ch[1], val);
}
void find(int u, int val) {
if(u == 0) return ;
if(node[u].val > val) {
printf("E");
find(node[u].ch[0], val);
}
if(node[u].val < val){
printf("W");
find(node[u].ch[1], val);
}
}
} tree;
int main() {
int q, val;
int T;
scanf("%d", &T);
while(T--) {
tree.clear();
scanf("%d", &n);
int root = 0;
for(int i = 1; i <= n; i++) {
scanf("%d", &val);
tree.insert(root, val);
}
scanf("%d", &q);
while(q--) {
scanf("%d", &val);
tree.find(root, val);
puts("");
}
}
return 0;
}