剑指offer之对称二叉树

本文介绍了一种判断二叉树是否对称的方法,通过对前序、中序和后序遍历的对称性检查,实现了判断二叉树与其镜像是否一致的功能。文章详细解释了在遍历过程中如何处理nullptr节点,确保算法正确性。

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

1.问题描述

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如:

//这是一个对称二叉树
//            8
//        6      6
//       5 7    7 5
//这不是一个对称二叉树
//            8
//        6      9
//       5 7    7 5
// 所有结点都有相同的值,树不对称
//               5
//              / \
//             5   5
//            /     \
//           5       5
//          /       /
//         5       5
// 所有结点都有相同的值,树不对称
//               5
//              / \
//             5   5
//            / \ / \
//           5  * *  5
//          / \     /  \
//         5   *   5   * 

2.分析

  • 对于第一个图:如果我们前序遍历,结果是:{8,6,5,7,6,7,5}。如果我们使用前序遍历的对称遍历算法,即先根节点,右子树,左子树,结果是:{8,6,5,7,6,7,5}。可以看出来,结果是一样的。
  • 但是,对于第三个图,因为值是一样的,那么还是按照上面的方法,那么,结果都是{5,5,5,5,5,5,5}。
  • 解决方法:如果遇到nullptr,我们也把nullptr加上去。对于图3,前序遍历结果是:{5,5,5,5,*,*,5,*,5,5,*},前序遍历的对称遍历结果是:{5,5,5,*,5,*,5,*,5,*,5} ,可以看出来,这两个结果不是一样的,所以不是对称二叉树。
  • 当然,除了前序遍历,中序,后序遍历都可以的。

3.源代码

前序遍历

bool isSymmetrical(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2)
{
    if(pRoot1 == nullptr && pRoot2 == nullptr)
        return true;

    if(pRoot1 == nullptr || pRoot2 == nullptr)
        return false;


    bool result = false;
    if(pRoot1->m_nValue == pRoot2->m_nValue)
        result = true;
    if(result)
        result = isSymmetrical(pRoot1->m_pLeft, pRoot2->m_pRight);
    if(result)
        result = isSymmetrical(pRoot1->m_pRight, pRoot2->m_pLeft);

    return result;
}

中序遍历:

//中序遍历
bool isSymmetrical_3(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2)
{
    if(pRoot1 == nullptr && pRoot2 == nullptr)
        return true;

    if(pRoot1 == nullptr || pRoot2 == nullptr)
        return false;

    bool result = isSymmetrical_3(pRoot1->m_pLeft,pRoot2->m_pRight);
    if(result && pRoot1->m_nValue != pRoot2->m_nValue)
        return false;

    if(result)
        result =  isSymmetrical_3(pRoot1->m_pRight,pRoot2->m_pLeft);

    return result;


}

后序遍历:

//后序遍历
bool isSymmetrical_4(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2)
{
    if(pRoot1 == nullptr && pRoot2 == nullptr)
        return true;

    if(pRoot1 == nullptr || pRoot2 == nullptr)
        return false;

    bool result = isSymmetrical_4(pRoot1->m_pLeft,pRoot2->m_pRight);


    if(result)
        result =  isSymmetrical_4(pRoot1->m_pRight,pRoot2->m_pLeft);

    if(result && pRoot1->m_nValue != pRoot2->m_nValue)
        result = false;

    return result;


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值