判断二叉搜索树是否相同,算法题

【代码来源】https://blog.csdn.net/RPG_Zero/article/details/100402135
【问题描述】
判断若干个序列是否为同一个二叉搜索树序列
【输入格式】
第一行输入一个数n,(1<=n<=20) 表示有n个序列需要判断,n= 0 的时候输入结束。第二行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。接下去的n行有n个序列,每个序列格式跟第一个序列(第二行输入的序列)一样,请判断该序列与第一个序列是否能组成同一棵二叉搜索树。
【输出格式】
如果序列相同则输出YES,否则输出NO
【样例输入】
2
567432
543267
576342
0
【样例输出】
YES
NO

【算法思想】由于判断两个二叉搜索树是否相同仅需要判断他们的中序编历和后序编历得出的结果是否相同即可,所以我们就要对这两个序列分别进行中序编历和后序编历

#include "pch.h"							//同下
#define _CRT_SECURE_NO_DEPRECATE			//运用了scanf,如果在vs中运行的话要加这句话
#include <iostream>
#include <stdio.h>
#include<string.h>

using namespace std;
struct node {
	node *left;
	node *right;
	int num;
}tree[105];				//静态数组

char str1[30], str2[30];//x表示原始的中后序编历,y表示后来的中后序编历
int cnt;			//静态数组中要使用的元素
int num;			//字符数组中要使用的元素

node *creat()		//申请新结点
{
	tree[cnt].left = tree[cnt].right = NULL;
	return &tree[cnt++];
}

node *build(int x, node*t)			
{
	if (t == NULL)
	{
		t = creat();
		t->num = x;
	}
	else if (x < t->num) 
	{
		t->left = build(x, t->left);
	}
	else if (x > t->num) 
	{
		t->right = build(x, t->right);
	}
	return t;
}

void in_order(node *root) {//中序遍历
	if (root == NULL) return;
	in_order(root->left);
	str2[num++] = root->num + '0';
	in_order(root->right);
}

void port_order(node *root)			//后序编历
{
	if (root == NULL)return;
	port_order(root ->left);
	port_order(root->right);
	str2[num++] = root->num + '0';
}
int main()
{
	int n;
	while (cin>> n&&n!=0)
	{
		scanf("%s", str1);						
		int len = strlen(str1);				//用strlen求x数组的长度
		cnt = 0; num = 0;
		node *t = NULL;
		for (int i = 0; i < len; i++)		//建立最开始的二叉排序树即二叉搜索树
		{
			t = build(str1[i] - '0',t);
		}
		in_order(t);
		port_order(t);					//开始编历
		for (int i = 0; i < num; i++)
		{
			str1[i] = str2[i];
		}
		while (n--)							//循环至输入n之后结束
		{
			cnt = 0; num = 0;
			scanf("%s", str2);
			int len = strlen(str2);
			node *tt = NULL;
			for (int i = 0; i < len; i++)	//建立用于比较的二叉搜索树
			{
				tt = build(str2[i] - '0', tt);
			}
			in_order(tt);					//进行编历
			port_order(tt);
			int i;
			for (i = 0; i < num; i++)
			{
				if (str1[i] != str2[i])
				{
					break;
				}
			}
			if (i == num)
			{
				cout << "YES" << endl;									//可输出比较结果进行判断是否正确
				/*cout << "编历结果如下:" << endl;
				cout << "原先的中后序编历结果:";
				for (int i = 0; i < num; i++)
					cout << str1[i];
				cout << endl;
				cout << "被比较的序列中后序编历结果:";
				for (int i = 0; i < num; i++)
					cout << str2[i];*/
			}
			else cout << "NO" << endl;
		}
	}
	return 0;
}

【PS】本人萌新一个,还在学习的路上,如有解释不对请多包涵,已备注代码出处

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值