【王道】判断两序列是否为同一二叉搜索树序列(C++)

【题意】

开始一个数n,表示有n个需要判断,n=0时输入结束,接下去一行是一个序列,没有重复数字,根据这个序列可以构造一棵二叉搜索树。接下来的n行有n个序列,判断每个序列是否与第一个序列组成同一个二叉搜索树

【思路】

为每一个序列构建二叉搜索树,然后判断其前序、中序遍历结果是否与第一个一样,一样的话就是同一个二叉搜索树。当然也可以选择中序和后序遍历结果,但必须包含中序遍历。

【注意】只有包含中序遍历的两种遍历顺序才能唯一的确定一棵二叉树。

#include<iostream>
#include<stack>
#include<string.h>
#include<iomanip>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
char pre[100];//储存目标序列的前序遍历结果
char in[100];//储存目标序列的中序遍历结果
char temp_pre[100];
char temp_in[100];
struct Node
{
	Node* l;
	Node* r;
	int c;
}Tree[100];
int loc,s;
Node* create()
{
	Tree[loc].l=Tree[loc].r=NULL;
	return &Tree[loc++];
}
void preorder(Node* T,char *a)//别忘了末尾加0
{
	a[s++]=T->c;
	if(T->l!=NULL)
		preorder(T->l,a);
	if(T->r!=NULL)
		preorder(T->r,a);
}
void inorder(Node* T,char *a)//别忘了末尾加0
{
	if(T->l!=NULL)
		preorder(T->l,a);
	a[s++]=T->c;
	if(T->r!=NULL)
		preorder(T->r,a);
}
Node* Insert(Node*T,int a)
{
	if(T==NULL)
	{
		T=create();
		T->c=a;
		return T;
	}
	else if(a>T->c)
		T->r=Insert(T->r,a);
	else if(a<T->c)
		T->l=Insert(T->l,a);
	return T;
}
int main(int argc, char const *argv[])
{
	int n,i;
	char str[100];
	while(cin>>n)
	{
		if(n==0)
			break;
		cin>>str;
		Node* T1=NULL;loc=0;

		for(i=0;str[i]!=0;i++)
		{
			T1=Insert(T1,str[i]);
		}

		s=0;preorder(T1,pre); pre[s]=0;
		s=0;inorder(T1,in); in[s]=0;
		
		
		while(n--)
		{
			cin>>str;
			T1=NULL;loc=0;
			for(i=0;str[i]!=0;i++)
			{
				T1=Insert(T1,str[i]);
			}
			s=0;preorder(T1,temp_pre);temp_pre[s]=0;
			s=0;inorder(T1,temp_in);temp_in[s]=0;
			if(strcmp(temp_in,in)==0&&strcmp(temp_pre,pre)==0)
				cout<<"Yes"<<endl;
			else
				cout<<"No"<<endl;
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值