二叉搜索树 HDU - 3791

二叉搜索树

Problem Description

判断两序列是否为同一二叉搜索树序列

Input

开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。

Output

如果序列相同则输出YES,否则输出NO

Sample Input

2
567432
543267
576342
0

Sample Output

YES
NO

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
	int data;  //数据域
	struct node *lchild,*rchild;  //左右子树
};
typedef struct node* Bit;
Bit inserttree(Bit t,int ch)
{
	if(t==NULL)
	{ 
		t= (struct node*)malloc(sizeof(struct node));
		t->data=ch;
		t->lchild=NULL;
		t->rchild=NULL;   
	}
	else if(ch>t->data)t->rchild=inserttree(t->rchild,ch);
	else t->lchild=inserttree(t->lchild,ch);
	return t;
} 
int flag=0;
void  check(Bit at,Bit bt)
{ 
	if(flag==1)return;
	if(at==NULL||bt==NULL)return; 
	if(at->data!=bt->data)flag=1; 
	else
	{
		check(at->lchild,bt->lchild);
		check(at->rchild,bt->rchild);
	}
	return ;
}
int main()
{
	int n;
	char a[12],b[12];
	while(scanf("%d",&n)&&n)
	{
		scanf("%s",a);
		Bit at=NULL;
		for(int i=0;i<strlen(a);i++)
		{ 
			at=inserttree(at,a[i]-'0');
		}
		while(n--)
		{
			flag=0; 
			scanf("%s",b); 
			if(strlen(a)!=strlen(b))  //长度不同,一定不同
			{
				printf("NO\n");
				continue;
			}
			Bit bt=NULL; 
			for(int i=0;i<strlen(b);i++)
			{ 
				bt=inserttree(bt,b[i]-'0');
			} 
			check(at,bt);
			if(flag==1)
			{
				printf("NO\n");
			}
			else
			{
				printf("YES\n");
			}
		}	
	}
	
	return 0;
} 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值