二叉搜索樹 hdu 3791

二叉搜索樹

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 17   Accepted Submission(s) : 11

Font: Times New Roman | Verdana | Georgia

Font Size:  

Problem Description

判斷兩序列是否爲同一二叉搜索樹序列

Input

開始一個數n,(1<=n<=20) 表示有n個需要判斷,n= 0 的時候輸入結束。
接下去一行是一個序列,序列長度小於10,包含(0~9)的數字,沒有重複數字,根據這個序列可以構造出一顆二叉搜索樹。
接下去的n行有n個序列,每個序列格式跟第一個序列一樣,請判斷這兩個序列是否能組成同一顆二叉搜索樹。

Output

如果序列相同則輸出YES,否則輸出NO

Sample Input

2
567432
543267
576342
0

Sample Output

YES
NO


一個基礎的建樹模型   只要把幾棵樹的結點位置放在數組裏面,。然後 比較數組··
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int a[1024],b[1024];
void chuan(string s,int c[]) //建樹 
{
	int i,j;
	int l=s.length();
	for(i=0;i<l;i++)
	{
		int t=s[i]-'0';
		for(j=1;j<2014;)
		{
			if(c[j]==-1)
			{
				c[j]=t;
				break;	
			}
			else if(c[j]>t) //左子樹 
			{
				j=j*2;
			}
			else  //右子樹 
			j=j*2+1;
		}
	}
}
int main()
{
	int n,i,j,k;
	string st1;
	string st2;
	while(cin>>n&&n)
	{
		for(i=0;i<1024;i++)
		{
			a[i]=-1;
		}
		cin>>st1;
		chuan(st1,a); //原樹 
		while(n--)
		{
			for(j=0;j<1024;j++)
			{
				b[j]=-1;
			}
			cin>>st2;
			chuan(st2,b);
			for(k=0;k<1024;k++) //比較 
			{
				if(a[k]!=b[k])
				break;
			}
			if(k==1024) cout<<"YES"<<endl;
			else cout<<"NO"<<endl;
		}
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章