HDU 3791 二叉搜索树

二叉搜索树

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

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

Source

浙大计算机研究生复试上机考试-2010年
 
 

一棵非空的二叉搜索树满足以下特征:
每个结点都有一个作为搜索依据的关键码,所有结点的关键码互不相同。
左子树(如果存在)上的所有结点的关键码均小于根结点的关键码。
右子树(如果存在)上的所有结点的关键码均大于根结点的关键码。
根结点的左右子树也都是二叉搜索树。

二叉搜索树又称为“二叉排序树”、“二叉查找树”、“二叉检索树”

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

const int N=2010;

char str[30];
int num1[N],num2[N];

void Insert(int num[N],int index,int x){
    if(num[index]==-1){
        num[index]=x;
        return ;
    }
    if(num[index]<x)
        Insert(num,index<<1,x);
    else
        Insert(num,index<<1|1,x);
}

int main(){

    //freopen("input.txt","r",stdin);

    int n;
    while(~scanf("%d",&n) && n){
        memset(num1,-1,sizeof(num1));
        scanf("%s",str);
        for(int i=0;str[i]!='\0';i++){
            int x=str[i]-'0';
            Insert(num1,1,x);
        }
        int flag;
        while(n--){
            scanf("%s",str);
            flag=1;
            memset(num2,-1,sizeof(num2));
            for(int j=0;str[j]!='\0';j++){
                int x=str[j]-'0';
                Insert(num2,1,x);
            }
            for(int j=0;j<N;j++)
                if(num1[j]!=num2[j]){
                    flag=0;
                    break;
                }
            if(flag)
                puts("YES");
            else
                puts("NO");
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jackge/p/2955777.html