剑指offer之对称二叉树

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;


}

猜你喜欢

转载自blog.csdn.net/zqw_yaomin/article/details/81735675