SDUT--2482--二叉排序树

二叉排序树

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

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

Input

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

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

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

Output

是,输出YES;不是,输出NO。每个输出占一行。

Sample Input

2
123456789
987654321
432156789
0

Sample Output

NO
NO

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct tree
{
    char data;
    struct tree *l, *r;
} *root, *root2;
struct tree *creat(char a, struct tree *root);
void judge(struct tree *root, struct tree *root2);
int flag;
int main()
{
    int n, i, l;
    char a[20], b[20];
    while(~scanf("%d", &n) && n)
    {
        scanf("%s", a);
        l = strlen(a);
        root = NULL;
        for(i = 0; i < l; i++) // root = NULL一定要写在循环外边
        {
            root = creat(a[i], root);
        }
        while(n--)
        {
            scanf("%s", b);
            root2 = NULL; // root = NULL一定要写在循环外边
            for(i = 0; i < l; i++)
            {
                root2 = creat(b[i], root2);
            }
            flag = 1;
            judge(root, root2);
            if(flag)
                printf("YES\n"); // 注意大小写
            else
                printf("NO\n");
        }
    }
    return 0;
}
struct tree *creat(char a, struct tree *root)
{
    if(!root)
    {
        root = (struct tree *)malloc(sizeof(struct tree));
        root->data = a;
        root->l = NULL;
        root->r = NULL;
    }
    else
    {
        if(a < root->data)
            root->l = creat(a, root->l);
        else
            root->r = creat(a, root->r);
    }
    return root;
};
void judge(struct tree *root, struct tree *root2)
{
    if(root && root2)
    {
        if(root->data != root2->data)
        {
            flag = 0;
            return ;
        }
        judge(root->l, root2->l);
        judge(root->r, root2->r);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WMYBlog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值