B - binary sort tree (compare two binary sort tree)

Description

Defined binary sort tree is: either an empty tree or a binary tree having the following properties: if its left subtree is not empty, then the value of the left sub-tree, all the nodes are less than its root node value; if its right subtree is not empty, then the value of the right sub-tree, all nodes are greater than the value of the root; its left and right sub-trees are binary sort tree. Today, we have to determine whether the two sequences of the same binary sort tree
Input

Start a number n, (1 <= n < = 20) expressed a need to determine n, n = 0 when the input end.
The next line is the sequence of a sequence length of less than 10, comprising a number (0 to 9), without repeating numbers, the sequence can be constructed in accordance with a binary sort tree.
The next n lines there are n sequences, each format with the first sequence, like, please determine whether the two sequences can be composed with a binary sort tree. (Data not guarantee free tree)
the Output

Sample

Input

2
123456789
987654321
432156789
0
Output

NO
NO

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
typedef struct node
{
    char data;
    struct node *r,*l;
} node,*Tree;
int n;
void creat( Tree&T,int m)
{
    if(T ==NULL)
    {
        T =(node*)malloc(sizeof(node)) ;
        T->r=NULL;
        T->l=NULL;
        T->data=m;
    }
    else
    {
        if(m<T->data)
        {
            creat(T->l,m);
        }
        else
        {
            creat (T->r,m);
        }
    }
}
int flag;
void Compare(Tree T1,Tree T2)
{
    if(!T1&&!T2)
        return ;
    else if(T1->data != T2->data)
    {
        flag = 1;
        return ;
    }
    else
    {
        Compare(T1->l,T2->l);
        Compare(T1->r,T2->r);
    }
}
int main()
{
    int n;
    while(~scanf("%d",&n)&&n)
    {
        if(n == 0)break;
        Tree T1=NULL;//注意
        char st[10];
        scanf("%s",st);
        int len=strlen(st);
        for(int i=0; i<len; i++)
        {
             creat(T1,st[i]);
        }
        char st1[10];
        while(n--)
        {
            flag=0;
            Tree T2=NULL;//注意
            scanf("%s",st1);
            for(int i=0; st1[i]!='\0'; i++)
            {
                creat(T2,st1[i]);
            }
            Compare(T1,T2);
            if(flag==1)
                printf("NO\n");
            else
                printf("YES\n");
        }
    }
    return 0;
}

Published 177 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/Fusheng_Yizhao/article/details/104869546