《算法笔记》9.4小节——数据结构专题(2)->二叉查找树(BST)->问题 B: 二叉搜索树

问题 B: 二叉搜索树

时间限制: 1 Sec  内存限制: 32 MB
提交: 340  解决: 171
[提交][状态][讨论版][命题人:外部导入]

题目描述

判断两序列是否为同一二叉搜索树序列

输入

开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。

输出

如果序列相同则输出YES,否则输出NO

样例输入

6
45021
12045
54120
45021
45012
21054
50412
0

样例输出

NO
NO
YES
NO
NO
NO

[提交][状态]

#include<iostream>
#include<string>
using namespace std;

struct node{
	int data;
	node *lchild,*rchild;
};

string s,temp;//s为样本,temp测试样例 
int a[15],b[15];//保存s和temp的整型数组 
string pres,pretemp;//s和temp的前序遍历序列 

node *newNode(int v){
	node *Node=new node;
	Node->data=v;
	Node->lchild=Node->rchild=NULL;
	return Node;
}

void insert(node *&root,int x){
	if(root==NULL){
		root=newNode(x);
		return;
	}
	if(root->data==x){
		return;
	}else if(x<root->data){
		insert(root->lchild,x);
	}else{
		insert(root->rchild,x);
	}
}

node *create(int data[],int n){
	node *root=NULL;
	for(int i=0;i<n;i++){
		insert(root,data[i]);
	}
	return root;
}

void s_preOrder(node *root){//s的先序遍历,保存为pres 
	if(root!=NULL){
//		cout<<root->data<<" ";
		pres+=(root->data+'0');
		s_preOrder(root->lchild);
		s_preOrder(root->rchild);
	}
}
void temp_preOrder(node *root){//temp的先序遍历,保存为pretemp 
	if(root!=NULL){
		pretemp+=(root->data+'0');
		temp_preOrder(root->lchild);
		temp_preOrder(root->rchild);
	}
}


int main(){
	int n;//n个数 
	cin>>n;
	 
	cin>>s;//输入样本s 
	for(int i=0;i<s.size();i++){//string转为int 
		a[i]=s[i]-'0';
	}
	node *news=create(a,s.size());
	s_preOrder(news);
	cout<<"样例前序遍历:"<<pres<<endl;
	
	while(n--){
		cin>>temp;//测试样例 
		pretemp.clear();
		if(temp.size()==s.size()){//如果测试与样例格式相同 
			for(int i=0;i<temp.size();i++){//string转为int 
				b[i]=temp[i]-'0'; 
			}
			node *newtemp=create(b,temp.size());
			temp_preOrder(newtemp);
			cout<<"测试前序遍历:"<<pretemp<<endl;
			if(pres==pretemp){
				cout<<"YES"<<endl;
			}else{
				cout<<"NO"<<endl; 
			}
		}
	}
	return 0;
}
发布了51 篇原创文章 · 获赞 7 · 访问量 7450

猜你喜欢

转载自blog.csdn.net/Jason6620/article/details/104077419
今日推荐