hdu 5444 遍历树+模拟

本文介绍了一种基于树结构的数据处理方法,包括如何通过前序遍历构建树,并利用中序遍历特性进行节点赋值。此外,还提供了一个算法示例,演示了如何查询从根节点到特定节点的路径。

点击打开链接


题意:树的结构固定 现在给树的节点赋值 

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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值