题意:树的结构固定 现在给树的节点赋值
they always number the room number from the east-most position to the west. //先左子树然后根最后右子树:即按照树的中序遍历顺序给树赋值1~n
The sequence is written as follows, it will go straight to visit the east-most room and write down every room it encountered along the way. After the first room is reached, it will then go to the next unvisited east-most room, writing down every unvisited room on the way as well until all rooms are visited.
//题目给出按照前序遍历给出节点的值 然后求根到某点的路径 :方法:建树+模拟即可
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
using namespace std;
const int M=2100;
int tot; //与题目编号无关
int a[M];//前序遍历
//The sequence is written as follows, it will go straight to visit the east-most room
//and write down every room it encountered along the way. After the first room is reached,
//it will then go to the next unvisited east-most room,
//writing down every unvisited room on the way as well until all rooms are visited.
//给出的seq是按前序遍历写出val的值
struct node{
int l,r,val;//val为中序遍历时的顺序
}tree[M];
void Init(int x)
{
tree[x].l=tree[x].r=0;//子树编号
}
void insert(int x,int val)//x为根,插入
{
if(tree[x].l&&val<tree[x].val) //如果左子树存在&&值小于根,插入到左子树
insert(tree[x].l,val);
else if(tree[x].r&&val>tree[x].val)
insert(tree[x].r,val);
else //根节点缺少子树
{
Init(tot);
tree[tot].val=val;
if(tree[x].val>val)
tree[x].l=tot;
else
tree[x].r=tot;
}
}
// they always number the room number from the east-most position to the west.
// 左子树为east 则 num值:左子树<根<右子树 正好就是中序遍历该树时的顺序
void query(int x,int val)
{
if(val==tree[x].val)
{
cout<<endl;
return;
}
if(tree[x].val>val)
{
cout<<"E";
query(tree[x].l,val);
}
else
{
cout<<"W";
query(tree[x].r,val);
}
}
int main()
{
int t;
cin>>t;
while(t--)
{
tot=1;
int n;
cin>>n;
// they always number the room number from the east-most position to the west.
// 左子树为east 则 左子树num<根<右子树
for(int i=1;i<=n;i++)//前序遍历
{
scanf("%d",&a[i]);
if(tot==1)//根节点
{
Init(tot);
tree[tot].val=a[i];
}
else
insert(1,a[i]);
tot++;
}
int q;
cin>>q;
while(q--)
{
int val;
cin>>val;
query(1,val);
}
}
return 0;
}
本文介绍了一种基于树结构的数据处理方法,包括如何通过前序遍历构建树,并利用中序遍历特性进行节点赋值。此外,还提供了一个算法示例,演示了如何查询从根节点到特定节点的路径。

105

被折叠的 条评论
为什么被折叠?



