PAT 是否为同一棵二叉搜索树

该代码实现了一个判断两棵二叉搜索树是否相等的程序。通过输入节点值构造两棵树,然后使用递归的isEqual函数进行比较,若所有节点数据相同且结构相同,则认为两棵树相等,输出"Yes",否则输出"No”。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <string.h>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
int n,l;
typedef struct dataStruct{
    dataStruct* left;
    dataStruct* right;
    int         data;


}*node;
void CreatTree(node &T, int dt){
    if(T == NULL){
        T  = new dataStruct();
        T->data = dt;
        T->left = NULL;
        T->right = NULL;
        return ;
    }
    if(T->data > dt){
        CreatTree(T->left, dt);
    }else{
        CreatTree(T->right, dt);
    }
}
bool isEqual(node t1,node t2){
    if(t1 != NULL && t2 != NULL){
        if(t1->data != t2->data){
            return false;
        }
        return (isEqual(t1->left,t2->left)&&isEqual(t1->right,t2->right));
    }else{
        if(t1 == NULL && t2 ==NULL){
            return true;
        }else{
            return false;
        }
    }


}
int main(){
    int w;
    int len1;
    node t1,t2;
    while(cin>>n && n != 0){
        cin>>l;
        t1 = NULL;
        for(int i = 0 ;i < n ;i++){
            cin>>w;
            CreatTree(t1,w);
        }
        for(int i =  0 ;i < l ;i++){
            t2 = NULL;
            for(int j = 0 ;j < n ;j++){
                cin>>w;
                CreatTree(t2, w);
            }
             if(isEqual(t1,t2)){
                    cout<<"Yes"<<endl;
            }else{
                    cout<<"No"<<endl;
            }
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值