Same Tree

Description:

Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

代码:

#include <iostream>
#include <stack>

#define Elementype int

using namespace std;



typedef struct TreeNode //树结点
{
    Elementype  val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(Elementype x) : val(x), left(nullptr), right(nullptr) {}
} *Tree;

//全局索引变量
int index = 0;


//使用先序遍历创建创建二叉树
void MakeBinaryTree(Tree &T, Elementype value[])
{
    Elementype  c = value[index++];
    if (c == '#')
        T = nullptr;
    else
    {
        T = new TreeNode(c);
        MakeBinaryTree(T->left, value);
        MakeBinaryTree(T->right, value);
    }

}

bool isSameTree(Tree T1, Tree T2)
{
    stack<Tree> sk;
    Tree p = nullptr;
    Tree q = nullptr;
    sk.push(T1);
    sk.push(T2);
    while (!sk.empty())
    {
        p = sk.top(); 
        sk.pop();
        q = sk.top();
        sk.pop();
        if (!p && !q)
            continue;
        if (!p || !q)
            return false;
        if (p->val != q->val)
            return false;

        sk.push(p->left);
        sk.push(q->left);

        sk.push(p->right);
        sk.push(q->right);

    }

    return true;
}

int main()
{
    Tree T1 = nullptr, T2 = nullptr,T3 = nullptr;

    //注意,每个结点都要有值,注意这里的取值不要等于35,即#
    Elementype data1[11] = { 3, 9, '#', '#', 20, 15, '#', '#', 7, '#', '#' };
    Elementype data2[11] = { 3, 9, '#', '#', 20, 15, '#', '#', 7, '#', '#' };
    Elementype data3[11] = { 3, 8, '#', '#', 20, 15, '#', '#', 7, '#', '#' };

    MakeBinaryTree(T1, data1);
    index = 0;
    MakeBinaryTree(T2, data2);
    index = 0;
    MakeBinaryTree(T3, data3);


    cout <<"T1 == T2 ? "<<boolalpha<<isSameTree(T1,T2) << endl;
    cout << "T1 == T3 ? " << boolalpha << isSameTree(T1, T3) << endl;

    system("pause");
    return 0;
}

测试:

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值