04-树4 是否同一棵二叉搜索树(25 分)

来源:互联网 发布:域名跟网址的区别 编辑:程序博客网 时间:2024/06/15 23:26

04-树4 是否同一棵二叉搜索树(25 分)

给定一个插入序列就可以唯一确定一棵二叉搜索树。然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到。例如分别按照序列{2, 1, 3}和{2, 3, 1}插入初始为空的二叉搜索树,都得到一样的结果。于是对于输入的各种插入序列,你需要判断它们是否能生成一样的二叉搜索树。

输入格式:

输入包含若干组测试数据。每组数据的第1行给出两个正整数N (10)和L,分别是每个序列插入元素的个数和需要检查的序列个数。第2行给出N个以空格分隔的正整数,作为初始插入序列。最后L行,每行给出N个插入的元素,属于L个需要检查的序列。

简单起见,我们保证每个插入序列都是1到N的一个排列。当读到N为0时,标志输入结束,这组数据不要处理。

输出格式:

对每一组需要检查的序列,如果其生成的二叉搜索树跟对应的初始序列生成的一样,输出“Yes”,否则输出“No”。

输入样例:

4 23 1 4 23 4 1 23 2 4 12 12 11 20

输出样例:

YesNoNo
此题考虑到若前序一致,后序一致就ok,(中序没用)
#include <cstdio>#include <cstdlib>#include <string>#define MAXSIZE 100int index = 0;//#define LOCALtypedef struct node {    int data;    struct node* l;    struct node* r;} Node, *tree;void insert(tree &root, int x) {    if(!root) {        root = (tree)malloc(sizeof(Node));        root->data = x;        root->l=root->r=NULL;    }    else {        if(x<root->data)            insert(root->l, x);        else if(x>root->data)            insert(root->r, x);        }}void PretravesalString(tree root, std::string& s) {    if(!root) return;    s[index++] = root->data + '0';    PretravesalString(root->l, s);    PretravesalString(root->r, s);}void PosttravesalString(tree root, std::string& s) {    if(!root) return;    PosttravesalString(root->l, s);    PosttravesalString(root->r, s);    s[index++] = root->data + '0';}int main(){#ifdef LOCAL    freopen("test.txt", "r", stdin);#endif    int N, L;    while(scanf("%d", &N) && N!=0) {        scanf("%d", &L);        int tmp;        tree ftree = NULL;        std::string prefstring(MAXSIZE, ' ');        std::string postfstring(MAXSIZE, ' ');        for(int i=1; i<=N; ++i) {            scanf("%d", &tmp);            insert(ftree, tmp);        }        PretravesalString(ftree, prefstring);        index = 0;        PosttravesalString(ftree, postfstring);        index = 0;        //std::cout << prefstring << " "<<postfstring<<'\n';        //std::cout << fstring << " "<<fstring.length();        //system("pause");        while(L--) {            tree Ttree = NULL;            std::string preTstring(MAXSIZE, ' ');            std::string postTstring(MAXSIZE, ' ');            for(int i=1; i<=N; ++i) {                scanf("%d", &tmp);                insert(Ttree, tmp);            }            PretravesalString(Ttree, preTstring);            index = 0;            PosttravesalString(Ttree, postTstring);            index = 0;            //std::cout << preTstring << "*"<<postTstring<<'\n';            if(prefstring == preTstring && postfstring == postTstring)                printf("Yes\n");            else                printf("No\n");        }    }    return 0;}


原创粉丝点击