东北大学842-2018【二叉树】判断两棵树是否相等

原始代码

void isequal(bitree *p,bitree *q,int n)
{
    if(p!=NULL&&q!=NULL)
    {
        int count=0;
        if(p.data==q.data)
            count++;
        isequal(p->lchild,q->lchcild,n)
        isequal(p->rchild,q->rchild,n)
        
    }
    if(count==n)
        cout<<"q树和p树相等"<<endl;
    else 
        cout<<false;
}

修改代码

void isequal(bitree p, bitree q, int& count, int n) {
    if (p != NULL && q != NULL) {
        if (p->data == q->data)
            count++;

        isequal(p->lchild, q->lchild, count, n);
        isequal(p->rchild, q->rchild, count, n);
    }
}

完整代码

#include <iostream>
using namespace std;

struct TreeNode {
    int data;
    struct TreeNode* lchild;
    struct TreeNode* rchild;
};

typedef struct TreeNode* bitree;

bitree createNode(int data) {
    bitree newNode = new TreeNode;
    newNode->data = data;
    newNode->lchild = NULL;
    newNode->rchild = NULL;
    return newNode;
}

bitree createBinaryTree1() {
    bitree root = createNode(1);
    root->lchild = createNode(2);
    root->rchild = createNode(3);
    root->lchild->lchild = createNode(4);
    root->lchild->rchild = createNode(5);
    root->rchild->lchild = createNode(6);
    root->rchild->rchild = createNode(7);
    return root;
}

bitree createBinaryTree2() {
    bitree root = createNode(1);
    root->lchild = createNode(2);
    root->rchild = createNode(3);
    root->lchild->lchild = createNode(4);
    root->lchild->rchild = createNode(5);
    root->rchild->lchild = createNode(6);
    root->rchild->rchild = createNode(7);  // 修改此处的节点值为 8
    return root;
}

void isequal(bitree p, bitree q, int& count, int n) {
    if (p != NULL && q != NULL) {
        if (p->data == q->data)
            count++;

        isequal(p->lchild, q->lchild, count, n);
        isequal(p->rchild, q->rchild, count, n);
    }
}

bool isTreeEqual(bitree p, bitree q, int n) {
    int count = 0;
    isequal(p, q, count, n);
    return count == n;
}

int main() {
    bitree p = createBinaryTree1();
    bitree q = createBinaryTree2();
    int n = 7;

    if (isTreeEqual(p, q, n)) {
        cout << "q树和p树相等" << endl;
    } else {
        cout << "q树和p树不相等" << endl;
    }

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值