zoukankan      html  css  js  c++  java
  • 二叉搜索树(王道)

    王道提到了一点,要判断两个树是否相同,需要遍历包括中序在内的至少两种方法,进行比较,如果都相同,才能确定两树相同。

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

    如果序列相同则输出YES,否则输出NO

    样例输入:
    2
    567432
    543267
    576342
    0
    样例输出:
    YES
    NO
    #include <iostream>
    #include<cstdio>
    #include<string.h>
    using namespace std;
    
    struct Node{
        Node* lchild;
        Node* rchild;
        int num;
    };
    struct Node Tree[50];
    int loc;
    
    Node *create(){//申请结点空间
        Tree[loc].lchild = Tree[loc].rchild = NULL;
        return &Tree[loc++];
    }
    char *str0;//当前正在保存字符串
    int *size0;//当前正在保存字符串中字符的个数
    
    char str1[50],str2[50];//保存二叉排序树结果,前序和中序的字符串连接
    int size1,size2;//保存在字符数组中遍历得到字符个数
    
    void preOrder(Node *T){//前序遍历
        if(T->lchild != NULL)
            preOrder(T->lchild);
        if(T->rchild != NULL)
            preOrder(T->rchild);
        str0[(*size0)++] = T->num+'0';//结点中字符放入正在保存的字符串中
    }
    
    void inOrder(Node *T){//中序遍历
        if(T->lchild != NULL)
            inOrder(T->lchild);
        str0[(*size0)++] = T->num+'0';
        if(T->rchild != NULL)
            inOrder(T->rchild);
    }
    
    Node *insertNode(Node *T,int x){//数字插入二叉树
        if(T == NULL){
            T = create();
            T->num = x;
        }
        else if(x < T->num)
            T->lchild =insertNode(T->lchild,x);
        else if(x > T->num)
            T->rchild = insertNode(T->rchild,x);
        return T;
    }
    int main()
    {
        int n;
        cin >> n;
        char str[50];
        scanf("%s",str);
        loc = 0;//初始化静态空间为未使用
        Node *T = NULL;
        for(int i=0;str[i] != 0;i++)
            T = insertNode(T,str[i]-'0');
        size1 = 0;
        str0 = str1;
        size0 = &size1;
        preOrder(T);
        inOrder(T);
        str1[size1] = 0;//第一个字符串的最后一个字符后添加空字符,方面使用字符串函数
        while(n--){
            memset(str, 0,sizeof(str));
            scanf("%s", str);
            Node *T1 = NULL;
        for(int i=0;i<n;i++)
            T1 = insertNode(T1, str[i]-'0');
        size2 = 0;
        str0 = str2;
        size0 = &size2;
        preOrder(T1);
        inOrder(T1);
        str2[size2] = 0;
        puts(strcmp(str1, str2) == 0 ? "YES" : "NO");//比较输出
        }
        return 0;
    }
  • 相关阅读:
    hadoop中namenode发生故障的处理方法
    开启虚拟机所报的错误:VMware Workstation cannot connect to the virtual machine. Make sure you have rights to run the program, access all directories the program uses, and access all directories for temporary fil
    Hbase的安装与部署(集群版)
    分别用反射、编程接口的方式创建DataFrame
    用Mapreduce求共同好友
    SparkSteaming中直连与receiver两种方式的区别
    privot函数使用
    Ajax无刷新显示
    使用ScriptManager服务器控件前后台数据交互
    数据库知识
  • 原文地址:https://www.cnblogs.com/xym4869/p/8548657.html
Copyright © 2011-2022 走看看