二叉搜索树,建立在二叉树之上:
对于每一棵子树
左儿子的值小于根节点,右儿子的值大于根节点
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn = 50000;
char a[maxn];
char b[maxn];
int tree1[maxn];
int tree2[maxn];
void insert(char ch, int *tree)//建立二叉搜索树
{
int rt = 1;
int value = ch - '0';//节点的键值
while(tree[rt] != -1)//递归建树
{
if(tree[rt] < value)
rt = 2 * rt + 1;
else
rt = 2 * rt;
}
tree[rt] = value;
}
void build(char *s , int *tree)
{
tree[1] = s[0] - '0';//将字符串第一个值加入树,作为根节点
for(int i = 1;s[i]; i ++)//循环字符串,将每个值加入树中
insert(s[i],tree);
}
int main(void)
{
int n;
while(cin>>n)
{
if(n == 0)
return 0;
cin>>a;
memset(tree1,-1,sizeof(tree1));
build(a,tree1);
while(n --)
{
cin>>b;
memset(tree2,-1,sizeof(tree2));
int flag = 0;
build(b,tree2);
for(int i = 0 ; i < 50000 ; i ++)
{
if(tree1[i] != tree2[i])
{
flag = 1;
break;
}
}
if(flag)
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
}
}
}
//可以输出tree1的值,看看树的结构