zoukankan      html  css  js  c++  java
  • 二叉排序树

    二叉排序树

    Time Limit: 1000MS Memory limit: 65536K

    题目描述

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

    输入

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

    输出

    示例输入

    2
    123456789
    987654321
    432156789
    0

    示例输出

    NO
    NO

    先建一棵二叉排序树,然后把先序遍历的值在s1数组里,然后在输入一组字符串,建二叉排序树,再把先序遍历的值存起来。
    比较两次先序遍历的值是否相等,如果相等,输出YES,否则输出NO

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    typedef struct node{
        char data;
        struct node *lchild;
        struct node *rchild;
    }Tree;
    
    int i, n, kk=0;
    char key;
    char s1[10000], s2[10000];
    
    Tree *Insert(Tree *t , char key)
    {
        if(t == NULL)
        {
            Tree *p;
            p = (Tree *)malloc(sizeof(Tree));
            p->data = key;
            p->lchild = NULL;
            p->rchild = NULL;
            t = p;
        }
        else
        {
            if(key < t->data)
                t->lchild = Insert(t->lchild, key);
            else
                t->rchild = Insert(t->rchild, key);
        }
        return t;
    }
    
    void InOrder1(Tree *t)
    {
        if(t!=NULL)
        {
            s1[kk++] = t->data;
            //printf("%c ", t->data);
            InOrder1(t->lchild);
            InOrder1(t->rchild);
        }
    }
    
    void InOrder2(Tree *t)
    {
        if(t!=NULL)
        {
            s2[kk++] = t->data;
            //printf("%c ", t->data);
            InOrder2(t->lchild);
            InOrder2(t->rchild);
        }
    }
    int main()
    {
        char str[10000];
        while(~scanf("%d", &n) && n)
        {
            memset(str, 0, sizeof(str));
            scanf("%s", str);
            Tree * t = NULL;
            for(i=0; i<strlen(str); i++)
            {
               t =  Insert(t, str[i]);
            }
            kk = 0;
            InOrder1(t);
            s1[kk] = '';
            for(i=0; i<n; i++)
            {
                memset(str, 0, sizeof(str));
                scanf("%s", str);
                t = NULL;
                for(int j=0; j<strlen(str); j++)
                {
                    t = Insert(t, str[j]);
                }
                kk = 0;
                InOrder2(t);
                s2[kk] = '';
                if(strcmp(s1, s2)==0)
                     printf("YES
    ");
                else printf("NO
    ");
            }
        }
        return 0;
    }



  • 相关阅读:
    树状数组
    POJ 1178 -- 国王和骑士
    read
    优先队列
    统计八连块
    1579、Function Run Fun(记忆化搜索)
    5488: 石子归并II (区间DP+环形DP+四边形不等式优化)
    4797: 能量项链(区间DP,环形DP)
    5936 桃子的矩阵快速幂
    Happy Necklace(找规律+矩阵快速幂)
  • 原文地址:https://www.cnblogs.com/6bing/p/4117738.html
Copyright © 2011-2022 走看看