7-4是否同一棵二叉搜索树 (25分)

!指针害死人

#include <iostream>
#include <stdlib.h>
#include <cstring>
#define ElementType int
#define maxsize 12

using namespace std;

typedef struct Bstree{
    ElementType data;
    struct Bstree *left;
    struct Bstree *right;
}bst,*BST;

//向二叉排序树中插入,递归
BST Insert(BST &tree, ElementType x);
//检查两棵二叉树的结构是否一致
bool CheckBstree(BST t1,BST t2);
//输入并构造二叉排序树
BST BuildBst(int len);




//向二叉排序树中插入,递归
//注意建树的时候要修改指针指向,必须传递引用/指针
BST Insert(BST &tree, ElementType x){
    if(!tree){
        //新建一个结点
        BST t = (BST)malloc(sizeof(struct Bstree));
        t->left = t->right = NULL;
        t->data = x;
        tree = t;
    }
    else if(tree->data>x)
        tree->left = Insert(tree->left,x);
    else if(tree->data<x)
        tree->right = Insert(tree->right,x);
    return tree;
}



//检查两棵二叉树的结构是否一致
bool CheckBstree(BST t1,BST t2){
    //根节点都为空
    if(!t1&&!t2)
        return true;
    //1个不存在,1个存在
    if((!t1&&t2)||(!t2&&t1))
        return false;
    //根节点不为空判断内容是否相同
    if(t1->data!=t2->data)
        return false;
    //递归左右子树
   return CheckBstree(t1->left,t2->left)&&CheckBstree(t1->right,t2->right);
}

//输入并构造二叉排序树
BST BuildBst(int len){
    int e;
    BST t = NULL;
    for(int i = 0 ; i<len; i++){
        cin>>e;
        Insert(t,e);
    }
    return t;
}

int main()
{
    int n,l;
    BST t;
    while(true){
        cin>>n;
        if(n==0)
            return 0;
        cin>>l;
        BST bt = BuildBst(n);
        for(int i = 0 ; i<l ; i++){
            t = BuildBst(n);
            CheckBstree(bt,t)?cout<<"Yes"<<endl:cout<<"No"<<endl;
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值