HDU 5444 Elven Postman

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值