HDU_3791 二叉搜索树

来源:互联网 发布:淘宝虚假交易处罚2016 编辑:程序博客网 时间:2024/05/22 06:53
          二叉搜索树
判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。 
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。 
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO 
Sample Input
25674325432675763420
Sample Output
YESNO
建立两个数组,根据搜索二叉树的构造原则(所有的结点左子树的所有结点都比自己小,右子树的所有结点都比自己大)将两个树分别存在两个数组中,然后比较两树的结点,有不同就是NO,相同YES。
#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int tree1[10000];int tree2[10000];void Insert(char word,int *tree){    int now=1;    int c=word-'0';    while(tree[now]!=-1)    {        if(tree[now]<c)            now=now*2+1;        else            now=now*2;    }    tree[now]=c;}void build(char *str,int *tree){    int l=strlen(str);    tree[1]=str[0]-'0';    for(int i=1; i<l; i++)        Insert(str[i],tree);}int main(){    int n;    char str[1000];    while(scanf("%d",&n)&&n)    {        memset(tree1,-1,sizeof(tree1));        memset(tree2,-1,sizeof(tree2));        scanf("%s",str);        build(str,tree1);        for(int i=0; i<n; i++)        {            int f=0;            memset(tree2,-1,sizeof(tree2));            scanf("%s",str);            build(str,tree2);            for(int j=0; j<1026; j++)            {                if(tree1[j]!=tree2[j])                {                    f=1;                    break;                }            }            if(!f)                printf("YES\n");            else printf("NO\n");        }    }}

原创粉丝点击