二叉搜索树(二叉排序搜索树)

二叉搜索树

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

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

题解:省赛有道树的形状相同的题,我还以为这个也是形状,错了几次,这个数值和树形都相同;想到省赛那题一直wa,现在想想要想判断树形相同,先序中序遍历都应该相同;我只是判断了位置,应该是不正确的。。。

这个不知道为啥只要先序就可以了。。。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef struct Node{
    Node *l, *r;
    char c;
    Node(){l = NULL; r = NULL;}
}*tree, Node;
void build(Node* &p, char c){
    if(p == NULL){
        p = new Node();
        p->c = c;
        return;
    }
    if(c < p->c)
        build(p->l, c);
    else
        build(p->r, c);
}

void InOrder(tree p, string& s){
    if(p == NULL)return;
    InOrder(p->l, s);
    s += p->c;
    InOrder(p->r, s);
}

void PreOrder(tree p, string& s){
    if(p == NULL)return;
    s += p->c;
    PreOrder(p->l, s);
    PreOrder(p->r, s);
}


int main(){
    int n;
    char dt[15];
    string ans1, ans2, s1, s2;
    while(scanf("%d", &n), n){
        Node *p;
        cin >> dt;
        p = NULL;
        for(int i = 0; dt[i]; i++){
            build(p, dt[i]);
        }
        ans1 = "";
        PreOrder(p, ans1);
        ans2 = "";
        InOrder(p, ans2);
    //    cout << ans1 << endl << ans2 << endl;
        for(int j = 0; j < n; j++){
            p = NULL;
            cin >> dt;
            for(int i = 0; dt[i]; i++){
                build(p, dt[i]);
            }
            s1 = "";
            PreOrder(p, s1);
            s2 = "";
            InOrder(p, s2);
    //        cout << s1 << endl << s2 << endl;
            if(s1 == ans1 && s2 == ans2)
                puts("YES");
            else
                puts("NO");
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/handsomecui/p/5574787.html