• [二叉查找树] 二叉搜索树


    题目描述

    判断两序列是否为同一二叉搜索树序列

    输入

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

    输出

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

    样例输入

    6 45021 12045 54120 45021 45012 21054 50412 0

    样例输出

    NO NO YES NO NO NO

    分析:在建立二叉查找树时,不同的插入序列可能得到相同的二叉查找树。这里写了一个比较函数,用于比较两颗二叉树是否相同。

    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <algorithm>
    #include <vector>
    #include <cmath>
    #include <queue>
    using namespace std;
    
    struct node
    {
        char data;
        node *lchild,*rchild;
    };
    
    bool judge(node * root1,node * root2)
    {
        if(root1==NULL&&root2!=NULL) return false;
        else if(root1!=NULL&&root2==NULL) return false;
        else if(root1==NULL&&root2==NULL) return true;
        else
        {
            if(root1->data!=root2->data) return false;
            else return judge(root1->lchild,root2->lchild)&&judge(root1->rchild,root2->rchild);
        }
    }
    
    void insert(node * &root,char data)
    {
        if(root==NULL)
        {
            root=new node;
            root->data=data;
            root->lchild=NULL;
            root->rchild=NULL;
            return ;
        }
        if(root->data==data) return ;
        else if(data<root->data)
        {
            insert(root->lchild,data);
        }
        else
        {
            insert(root->rchild,data);
        }
    }
    
    int main()
    {
        int n;
        while(cin>>n)
        {
            if(n==0) break;
            string input;
            node * root=NULL;
            cin>>input;
            for(int i=0;i<input.length();i++)
            {
                insert(root,input[i]);
            }
            
            string tmp;
            for(int i=0;i<n;i++)
            {
                node * test_tree=NULL;
                cin>>tmp;
                for(int j=0;j<tmp.length();j++)
                {
                    insert(test_tree,tmp[j]);
                }
                if(judge(root,test_tree))
                {
                    cout<<"YES"<<endl;
                }
                else
                {
                    cout<<"NO"<<endl;
                }
            }
            
            
        }
        return 0;
    }
  • 相关阅读:
    Linux命令汇总(二)
    关于pyspark
    关于CDH
    hive通过spark导入hbase
    CentOS7的网络配置
    TTY,Console以及Terminal
    docker的操作
    docker安装与操作
    Wmware Player中Linux挂载U盘
    Mesos和Marathon
  • 原文地址:https://www.cnblogs.com/xiongmao-cpp/p/6431233.html
Copyright © 2020-2023  润新知