二叉排序树(判断是否同树)

Problem Description

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

Input

开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。

接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉排序树。

接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉排序树。(数据保证不会有空树)

Output

Sample Input

2
123456789
987654321
432156789
0

Sample Output

NO
NO

Hint

Source

#include<bits/stdc++.h>
using namespace std;
struct node
{
    node *l,*r;
    int data;
};
node *Insert(node *root,int x)
{
    if(root==NULL)
    {
        root=new node;
        root->l=NULL;
        root->r=NULL;
        root->data=x;
    }
    else
    {
        if(x<root->data)
            root->l=Insert(root->l,x);
        else
            root->r=Insert(root->r,x);
    }
    return root;
}


bool show(node *root,node *root1)
{
    if(root==NULL&&root1==NULL)  //最底层递归条件
        return 1;
    if(root&&root1)
    {
        if(root->data!=root1->data)
            return 0;
        else if(show(root->l,root1->l)&&show(root->r,root1->r))//一步一步左右子树全为1才是1
            return 1;
    }
    return 0;
}

int main()
{
    int n;
    char s[100];
    while(cin>>n&&n)
    {
        cin>>s;
        int len=strlen(s);
        node *root=new node;
        root=NULL;
        for(int i=0; i<len; i++)
            root=Insert(root,s[i]-'0');
        while(n--)
        {
            cin>>s;
            node *root1=new node;
            root1=NULL;
            int len=strlen(s);
            for(int i=0;i<len;i++)
            {
                root1=Insert(root1,s[i]-'0');
            }
            int x=show(root,root1);
            if(x==1)
                cout<<"YES"<<endl;
            else
                cout<<"NO"<<endl;
        }
    }
    return 0;
}


/***************************************************
User name: ACM18171信科1801张林
Result: Accepted
Take time: 0ms
Take Memory: 228KB
Submit time: 2019-02-26 14:10:09
****************************************************/

猜你喜欢

转载自blog.csdn.net/weixin_43824158/article/details/87934054