二叉排序树


二叉排序树

 

Time Limit: 1000MS Memory limit: 65536K

题目描述

二叉排序树的定义是:或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。 今天我们要判断两序列是否为同一二叉排序树

输入

开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉排序树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉排序树。(数据保证不会有空树)

输出

 

示例输入

2
123456789
987654321
432156789
0

示例输出

NO
NO

提示

 

来源

 

示例程序

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

struct node
{
    char data;
    struct node *lch,*rch;
};
int k,a,b,c;
void creat(struct node *&root,char ch)//引用root(c++),建立二叉排序树
{
    if(root==NULL)
    {
        root=(struct node *)malloc(sizeof(struct node));
        root->lch=NULL;
        root->rch=NULL;
        root->data=ch;
    }
    else
    {

        if(ch < root->data)
            creat(root->lch,ch);
        else
            creat(root->rch,ch);
    }
}
void pre(struct node *root,char *str)
{
    if(root)
    {
        str[k++]=root->data;
        pre(root->lch,str);
        pre(root->rch,str);
    }
}//保存先序遍历的顺序
void mid(struct node *root,char *str)
{
    if(root)
    {
        mid(root->lch,str);
        str[a++]=root->data;
        mid(root->rch,str);
    }
}//保存中序遍历顺序
void last(struct node *root,char *str)
{
    if(root)
    {
        last(root->lch,str);
        last(root->rch,str);
        str[b++]=root->data;
    }
}//保存后序遍历顺序
int main()
{
    int n,i;
    char st[15],st1[15];
    char preor[15],midor[15],las[15];
    while(scanf("%d%*c",&n),n)
    {
        scanf("%s",st);
        struct node *root=NULL;
        int len=strlen(st);
        for(i=0;i<len;i++)
            creat(root,st[i]);
        k=0;a=0;b=0;
        pre(root,preor);//将先序遍历的结果传递到preor数组中
        preor[k]='\0';
        //printf("%s\n",preor);
        mid(root,midor);//用midor储存中序遍历结果
        midor[a]='\0';
        //printf("%s\n",midor);
        last(root,las);//las储存后序遍历结果
        las[b]='\0';
        //printf("%s\n",las);
        while(n--)
        {
            scanf("%s",st1);
            if(strcmp(preor,st1)==0 || strcmp(midor,st1)==0 || strcmp(las,st1)==0)
                printf("YES\n");//如果输入的字符串st的遍历先序,中序,后序中有一个与输入字符串相等,则输出YES
            else
                printf("NO\n");//否则,输出NO
        }
    }
    return 0;
}

 

posted @ 2014-11-24 23:20  夏迩  阅读(150)  评论(0)    收藏  举报