数据结构第四章(两个序列是否是同一棵二叉搜索树)

两个序列是否对应相同搜索树的判别:

算法1:分别建两棵搜索树的判别方法,根据两个序列分别建树,再判别树是否一样
算法2:不建树的判别方法。
算法3:建一棵树,再判别其他序列是否与该树一致

方法:在树T中按顺序搜索序列中的每个数
          如果每次搜索所经过的结点在前面均出现过,则一致    
          否则(某次搜索中遇到前面未出现的结点),则不一致

MakeTree(int N) //建立具有N个数的二叉搜索树  返回搜索树根节点的地址

jugde(BSTree T,int N)

功能 接受N个数组成的序列并与二叉搜索树T比较  判断序列是否会形成与T相同的搜索树。返回True或者False

check(BSTree T,int V) 判断数值V在搜索树中的位置是否与在需要判断序列所形成的二叉树的位置相同

Reset(T) 将二叉搜索树的结点所有flag归为0

Free(T) 将搜索树的结点内存释放

#include<stdio.h>
#include<stdlib.h>

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INSEASIBLE -1
#define OVERFLOW -2
typedef struct BSTNode *BSTree;
typedef int ElemType;
typedef int Status;
typedef struct BSTNode
{
	ElemType V;
	struct BSTNode *lchild,*rchild;
	int flag;
}BSTNode;
BSTree Insert(BSTree BST,ElemType X)
{
	if(!BST)
	{
		BST=(BSTree)malloc(sizeof(BSTNode));
		BST->V=X;
		BST->flag=0;
		BST->lchild=BST->rchild=NULL;
	}
	else
	{
		if(X<BST->V)
		{
			BST->lchild=Insert(BST->lchild,X);
		}
		else if(X>BST->V)
		{
			BST->rchild=Insert(BST->rchild,X);
		}
	}
	return BST;           //返回插入后的根节点地址 
}
BSTree MakeTree(int N)
{
	int i,V;
	BSTree BST=NULL,T=NULL;       //BST指的是树的根结点,T指的是插入元素的子树根节点 
	scanf("%d",&V);
	BST=Insert(BST,V);
	T=BST; 
	for(i=1;i<N;i++)
	{
		scanf("%d",&V);
		T=Insert(T,V);
	}
	return BST;
}
Status Check(BSTree BST,int V)
{
	if(BST->flag)
	{
		if(V<BST->V)
		{
			return Check(BST->lchild,V);
		}
		else if(V>BST->V)
		{
			return Check(BST->rchild,V);
		}
		else
		{
			return FALSE;
		}
	}
	else
	{
		if(V==BST->V)
		{
			BST->flag=1;
			return TRUE;
		}
		else return FALSE;
	}
}
Status Judge(BSTree BST,int N)
{
	int i,V,flag=1;  //flag=1标志目前一致 
	for(i=0;i<N;i++)
	{
		scanf("%d",&V);
		if(flag&&!Check(BST,V)) flag=0;
	}
	if(flag) return TRUE;
	return FALSE;
}
void Reset(BSTree BST)
{
	if(BST->lchild)
	{
		Reset(BST->lchild);
	}
	else if(BST->rchild) Reset(BST->rchild);
	BST->flag=0;
}
void Free(BSTree BST)
{
	if(BST->lchild) Free(BST->lchild);
	else if(BST->rchild) Free(BST->rchild);
	free(BST);
}
int main()
{
	int N,L,i;
	BSTree BST;
	scanf("%d",&N);
	while(N)
	{
		scanf("%d",&L);
		BST=MakeTree(N);
		for(i=0;i<L;i++)
		{
			if(Judge(BST,N)) printf("Yes\n");
			else printf("No\n");
			Reset(BST);
		}
		Free(BST);	
		scanf("%d",&N);
	}
 } 

猜你喜欢

转载自blog.csdn.net/a13683857889/article/details/86834470
今日推荐