hdu 3791 二叉搜索树

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;

typedef struct node *bst;
typedef struct node
{
    bst left,right;
    int data;
};

int a[20],b[20],cnt;

bst insert(int t,bst p)//插入结点
{
    if(!p)
    {
        p=(bst)malloc(sizeof(struct node));
        p->data=t;
        p->left=p->right=NULL;
    }
    else
    {
        if(t<p->data)
        {
            p->left=insert(t,p->left);
        }
        else if(t>p->data)
        {
            p->right=insert(t,p->right);
        }
    }
    return p;
}
void preorder(bst p)//先序遍历
{
    if(p)
    {
        b[cnt++]=p->data;
        preorder(p->left);
        preorder(p->right);
    }
}

int main()
{
    int n,i,t,j;
    char s[20];
    while(~scanf("%d",&n)&&n)
    {
        scanf("%s",s);
        bst root=NULL;
        int len=strlen(s);
        for(i=0; i<len; i++)
        {
            t=s[i]-'0';
            root=insert(t,root);
        }
        cnt=0;
        preorder(root);
        for(i=0; i<len; i++)
        {
            a[i]=b[i];
        }

        for(j=0; j<n; j++)
        {
            scanf("%s",s);
            root=NULL;
            len=strlen(s);
            for(i=0; i<len; i++)
            {
                t=s[i]-'0';
                root=insert(t,root);
            }
            cnt=0;
            preorder(root);

            for(i=0; i<len; i++)
                if(a[i]!=b[i]) break;
            if(i<len) printf("NO
");
            else printf("YES
");
        }


    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/

原文地址:https://www.cnblogs.com/xryz/p/4848036.html