二叉搜索树
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 6349 Accepted Submission(s): 2842
Problem Description
判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO
Sample Input
25674325432675763420
Sample Output
YESNO
题解:
二叉搜索树:左子树小于根节点,右子树大于跟节点。
建树然后判断是否相等即可。
链表代码:
#include<bits/stdc++.h>
using namespace std;
int cnt;
struct node
{
int x;
node *l,*r;
node()
{
l=r=NULL;
}
};
void buildtree(struct node *&root,int x)
{
if(!root)
{
root=new node();
root->x=x;
return;
}
if(x<root->x) buildtree(root->l,x);
else buildtree(root->r,x);
}
void get(node *root,int *t)
{
if(!root)return;
t[cnt++]=root->x;
get(root->l,t);
get(root->r,t);
}
int main()
{
int n;
while(~scanf("%d",&n)&&n)
{
int i,j;
char t1[22],t2[22];
int a1[22],a2[22];
scanf("%s",&t1);
node *root1=NULL;
int L=strlen(t1);
for(int i=0;i<L;i++)
{
buildtree(root1,t1[i]-'0');
}
cnt=0;
get(root1,a1);
for(int i=0;i<n;i++)
{
scanf("%s",&t2);
node *root2=NULL;
for(int j=0;j<L;j++)
buildtree(root2,t2[j]-'0');
cnt=0;
get(root2,a2);
bool bb=0;
for(int j=0;j<L;j++)
{
if(a1[j]!=a2[j])
bb=1;
}
if(bb)printf("NO\n");
else printf("YES\n");
}
}
return 0;
}
数组代码:
#include<cstdio>
#include<string.h>
using namespace std;
char t1[22],t2[22];
int a1[22],a2[22],tree1[20002],tree2[20002];
void buildtree(int *t,int rt,int x)
{
if(t[rt]==-1)
{
t[rt]=x;return;
}
if(x<t[rt])buildtree(t,rt<<1,x);
else buildtree(t,rt<<1|1,x);
}
int main()
{
int n;
while(~scanf("%d",&n)&&n)
{
memset(tree1,-1,sizeof(tree1));
scanf("%s",&t1);
int L=strlen(t1);
for(int i=0;i<L;i++)
buildtree(tree1,1,t1[i]-'0');
for(int i=0;i<n;i++)
{
memset(tree2,-1,sizeof(tree2));
scanf("%s",&t2);
for(int j=0;j<L;j++)
buildtree(tree2,1,t2[j]-'0');
bool bb=1;
for(int j=0;j<20000;j++)
if(tree1[j]!=tree2[j])
bb=0;
if(bb)printf("YES\n");
else printf("NO\n");
}
}
return 0;
}