判断二叉排序树是否相同

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<string>
using namespace std;
struct binarysearchnode {
	int value;
	binarysearchnode* lchild;
	binarysearchnode* rchild;
};//定义二叉查找树
typedef binarysearchnode* binarysearchtree;
//插入
binarysearchtree insert(binarysearchtree tree, int value)
{
	binarysearchnode *temp = tree;
	binarysearchnode *parent = NULL;//插入位置父节点
	while (temp != NULL)//寻找插入位置
	{
		parent = temp;
		if (temp->value < value)
		{
			temp = temp->rchild;
		}
		else {
			temp = temp->lchild;
		}
	}
	temp = new binarysearchnode();
	temp->value = value;
	if (tree == NULL)
	{
		tree = temp;
	}
	else
	{
		if (parent->value > value)
			parent->lchild = temp;
		else
			parent->rchild = temp;
	}
	return tree;
}
//前序
int flag = 0;
void pre(binarysearchtree tree, int *p)
{
	if (tree != NULL)
	{
		p[flag++] = tree->value;
		pre(tree->lchild,p);
		pre(tree->rchild,p);
	}
}
/*//中序
void in(binarysearchtree tree, int *p)
{
	if (tree != NULL)
	{
		in(tree->lchild, p);
		p[flag++] = tree->value;
		in(tree->rchild, p);
	}
}*/

int main()
{
	int n,k;
	string s;
	binarysearchtree tree;
	int min[10];//记录被比较二叉排序树前序
	//int min1[10];//记录被比较二叉排序树中序
	int cmp[10];//记录要比较二叉排序树前序
	//int cmp1[10];//记录要比较二叉排序树中序
	while (cin >> n)
	{
		if (n == 0) break;
		tree = NULL;
		cin >> s;
		int l = s.size();
		for (int j = 0; j < l; j++)
		{
			int va = s[j] - '0';
			tree = insert(tree, va);
		}
		flag = 0;
		pre(tree, min);
		while (n--)
		{
			cin >> s;
			tree = NULL;
			for (int j = 0; j < l; j++)
			{
				int va = s[j] - '0';
				tree = insert(tree, va);
			}
			flag = 0;
			pre(tree, cmp);
			for (k = 0; k < l; k++)
			{
				if (min[k] != cmp[k])
				{
					cout << "NO" << endl;
					break;
				}
			}
			if (k == l)
				cout << "YES" << endl;
		}
	}
	return 0;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值