二叉搜索树//二叉搜索树

题目:

 

二叉搜索树

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6945    Accepted Submission(s): 3077

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>

void initial(int a[], int n)
{
    for(int i = 0; i < n; i++)
        a[i] = -1;
}

void insert(int a[], int x)
{
    int pos = 1;
    while(a[pos] != -1)
    {
        if(x < a[pos])
            pos = 2*pos;
        else 
            pos = 2*pos+1;
    }
    a[pos] = x;
}

bool isequal(int a[], int b[], int n)
{
    for(int i = 0; i < n; i++)
    {
        if(a[i] != b[i])
            return false;
    }
    return true;
}

int main()
{
    using namespace std;
    int n;
    int N = 1000;
    int tree[N];
    int test[N];
    while(cin >> n && n != 0)
    {
        string str;
        cin >> str;
        initial(tree,N);
        for(int i = 0; i < str.length(); i++)
            insert(tree,str[i]-'0');
        while(n--)
        {
            cin >> str;
            initial(test,N);
            for(int i = 0; i < str.length(); i++)
                insert(test,str[i]-'0');
            bool ans = isequal(tree,test,N);
            if(ans)
            printf("YES\n");
            else
            printf("NO\n");    
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9218908.html