二叉排序树

来源:互联网 发布:罪恶之城和亵渎 知乎 编辑:程序博客网 时间:2024/06/05 19:24

二叉排序树

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

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

输入

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

输出

 

示例输入

21234567899876543214321567890

示例输出

NONO

提示

 

来源

 
#include<bits/stdc++.h>using namespace std;typedef struct node{    int data;    struct node *lchild,*rchild;}BinaryNode,*BinarySortTree;char b[50];int k;int create_BinarySortTree(BinarySortTree &T,int e){    if(T==NULL)    {        T= new BinaryNode ;        T->data=e;        T->lchild=NULL;        T->rchild=NULL;    }    else    {        if(e<=T->data)        {                create_BinarySortTree(T->lchild,e);        }        else            {                create_BinarySortTree(T->rchild,e);            }        }    return 0;}void preorder(BinarySortTree T){    if(T)    {   b[k++]=T->data+'0';        preorder(T->lchild);        preorder(T->rchild);    }}int main(){    BinarySortTree T;    int n,i,j;    char a[50],c[50];    while(cin>>n)    {        i=0,k=0;        T=NULL;        if(n==0) break;        else        {            cin>>a;            int len = strlen(a);        for(j=0;j<len;j++)        {            a[j]=a[j]-'0';            create_BinarySortTree(T,a[j]);        }        preorder(T);        while(n--)        {            cin>>c;            int flag =0 ;        for(int j=0;j<len;j++)        {            if(c[j]!=b[j])            {                flag=1;                break;            }        }        if(flag)            cout<<"NO"<<endl;        else            cout<<"YES"<<endl;        }    }    }}

0 0