栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【牛客网】KY124 二叉搜索树

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【牛客网】KY124 二叉搜索树


判断是否为同一二叉搜索树,首先就是要构造成二叉搜索树,则若是数据是一样的,那么中序遍历一定是一样的,因此中序遍历无法判断是否为同一二叉搜索树,但是其他遍历方式如先序遍历、后序遍历和层序遍历,则都能够判断,因此我采用的是先序遍历进行判断:

#include
#include

using namespace std;

struct TreeNode{
    int data;
    struct TreeNode *lchild, *rchild;
    TreeNode(int d): data(d), lchild(nullptr), rchild(nullptr){}
};

TreeNode* insert(TreeNode *root, int x){
    if(root == nullptr) root = new TreeNode(x);
    else if(x < root->data) root->lchild = insert(root->lchild, x);
    else if(x > root->data) root->rchild = insert(root->rchild, x);
    return root;
}

bool judge(TreeNode *root, TreeNode *root1){
    if(root == nullptr && root1 == nullptr) return true;
    if(root->data != root1->data) return false;
    else return judge(root->lchild, root1->lchild) && judge(root->rchild, root1->rchild);
}

int main(){
    int n;
    string str, str1;
    while(scanf("%d", &n) != EOF){
        if(n == 0) break;
        cin>>str;
        int k = str.size();
        TreeNode *root = nullptr;
        for(int i = 0;i < k;i++) root = insert(root, str[i] - '0');
        while(n--){
            cin>>str1;
            k = str1.size();
            TreeNode *root1 = nullptr;
            for(int i = 0;i < k;i++) root1 = insert(root1, str1[i] - '0');
            if(judge(root, root1)) printf("YESn");
            else printf("NOn");
        }
    }
    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/722156.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号