zoukankan      html  css  js  c++  java
  • SDUT ACM 2482 二叉排序树 Anti

    题目描述

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

    输入

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

    输出

    示例输入

    2
    123456789
    987654321
    432156789
    0

    示例输出

    NO
    NO
     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<string.h>
     4 
     5 //**********变量定义与函数声明**********
     6 int cnt; //用来生成先序遍历的字符串
     7 struct node
     8 {
     9     char data;
    10     struct node *left, *right;
    11 };
    12 void build(struct node **p, char k); //把k插入二叉排序树
    13 void preorder(struct node *p, char *s); //先序遍历
    14 void trans(char *s); //把二叉排序树的先序遍历转化成字符串
    15 void del(struct node *p); //释放内存
    16 //**********变量定义与函数声明**********
    17 
    18 int main()
    19 {
    20     int n;
    21     char first[20], second[20];
    22     while(~scanf("%d%*c", &n) && n)
    23     {
    24         trans(first);
    25         while(n--)
    26         {
    27             trans(second);
    28             printf("%s\n", strcmp(first, second) ? "NO" : "YES");
    29         }
    30     }
    31     return 0;
    32 }
    33 
    34 void build(struct node **p, char k)
    35 {
    36     if(*p == NULL)
    37     {
    38         *p = (struct node *)malloc(sizeof(struct node));
    39         (*p)->data = k;
    40         (*p)->left = (*p)->right = NULL;
    41     }
    42     else if((*p)->data > k)
    43         build(&(*p)->left, k);
    44     else build(&(*p)->right, k);
    45 }
    46 
    47 void preorder(struct node *p, char *s)
    48 {
    49     if(p == NULL)return;
    50     s[cnt++] = p->data;
    51     preorder(p->left, s);
    52     preorder(p->right, s);
    53 }
    54 
    55 void del(struct node *p)
    56 {
    57     if(p == NULL)return;
    58     del(p->left);
    59     del(p->right);
    60     free(p);
    61 }
    62 
    63 void trans(char *s)
    64 {
    65     char num[30];
    66     cnt = 0;
    67     gets(num);
    68     struct node *root = NULL;
    69     for(int i = 0; num[i]; i++)
    70         build(&root, num[i]);
    71     preorder(root, s);
    72     s[cnt] = 0;
    73     del(root);
    74 }
  • 相关阅读:
    阿里测试工程师教你自动化测试如何准备测试数据
    同一个tomcat下部署多个springboot项目时,springboot项目无法正常启动的问题
    ant desgin pro 跨页面传参
    富兰克林的人生信条
    node 一拉管理工具 yarn安装(npm的替代品)
    python pip 安装包下载过慢的解决方法 socket.timeout: The read operation timed out
    springBoot 文件下载
    Excel无法打开文件xxx.xlsx,因为文件格式或文件扩展名无效。请确定文件未损坏,并且文件扩展名与文件的格式匹配
    MYSQL like 模糊查询 分字查询
    人人译视界-给视频添加srt字幕
  • 原文地址:https://www.cnblogs.com/wolfred7464/p/2996476.html
Copyright © 2011-2022 走看看