数据结构与算法题目集(中文)7-4 是否同一棵二叉搜索树 (25分) (二叉搜索树中建立、判断)

1.题目

给定一个插入序列就可以唯一确定一棵二叉搜索树。然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到。例如分别按照序列{2, 1, 3}和{2, 3, 1}插入初始为空的二叉搜索树,都得到一样的结果。于是对于输入的各种插入序列,你需要判断它们是否能生成一样的二叉搜索树。

输入格式:

输入包含若干组测试数据。每组数据的第1行给出两个正整数N (≤10)和L,分别是每个序列插入元素的个数和需要检查的序列个数。第2行给出N个以空格分隔的正整数,作为初始插入序列。最后L行,每行给出N个插入的元素,属于L个需要检查的序列。

简单起见,我们保证每个插入序列都是1到N的一个排列。当读到N为0时,标志输入结束,这组数据不要处理。

输出格式:

对每一组需要检查的序列,如果其生成的二叉搜索树跟对应的初始序列生成的一样,输出“Yes”,否则输出“No”。

输入样例:

4 2
3 1 4 2
3 4 1 2
3 2 4 1
2 1
2 1
1 2
0

输出样例:

Yes
No
No

2.题目分析

1.首先需要注意本题中的结构体,因为我的方法是要实实在在使用指针建立二叉搜索树而不是使用数组实现

2.在测试的过程中是使用了struct结构体数组来存放待检测的二叉搜索树

3.注意二叉搜索树中插入(也就是建立)、判断函数的写法,这些都是基础操作,很久不看可能会生疏

3.代码

// typedef struct NODE{
//     int Data;
//     struct NODE *Left;
//     struct NODE *Right;
// } Tree;

#include<iostream>
using namespace std;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode {
	int Data;
	BinTree Left;//注意这里使用的BinTree
	BinTree Right;
};
BinTree Insert(BinTree BST, int X);
bool judge(BinTree BST, BinTree BSTtemp);
int main()
{
	BinTree BST;
	BST = NULL;
	int n, l,temp;
	cin >> n;
	if (n != 0)
		cin >> l;
	while (n!=0)
	{
		BST = NULL;
		for (int i = 0;i < n;i++)
		{
			cin >> temp;
			BST=Insert( BST, temp);
		}

		BinTree BSTlist[110] = {NULL};//思路:使用一个结构体指针数组来存放待检查的搜索树
		for (int i = 0;i < l;i++)
		{
			for (int j = 0;j < n;j++)
			{
				cin >> temp;
				BSTlist[i]=Insert(BSTlist[i], temp);
			}
			bool a=judge(BST, BSTlist[i]);
			if (a == true)cout << "Yes" << endl;
			else cout << "No" << endl;
		}
		cin >> n;
		if (n!= 0)
			cin >> l;
	}


	return 0;
}

BinTree Insert(BinTree BST, int X)
{
	if (BST == NULL)
	{
		 BST = (BinTree)malloc(sizeof(struct TNode));
		BST->Left = BST->Right = NULL;
		BST->Data = X;
	}

	else 
	{
		if(X < BST->Data)
			BST->Left = Insert(BST->Left, X);//注意这里的格式,要加上前面的BST->Left!!!
	else if(X > BST->Data)
		BST->Right = Insert(BST->Right, X);
	}

	return BST;
}

bool judge(BinTree BST, BinTree BSTtemp)
{
	if ((BST == NULL&&BSTtemp != NULL) || (BST != NULL&&BSTtemp == NULL))
		return false;
	else if (BSTtemp==NULL&&BST == NULL)
		return true;
	else {
		if(BST->Data != BSTtemp->Data)
			return false;
		else
		{
			bool a = judge(BST->Left, BSTtemp->Left);
			bool b = judge(BST->Right, BSTtemp->Right);
			if (a == true && b == true)
				return true;
			else
				return false;
		}
	}
原文地址:https://www.cnblogs.com/Jason66661010/p/12789031.html