美文网首页
对称的二叉树

对称的二叉树

作者: gaookey | 来源:发表于2021-11-15 11:52 被阅读0次

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

    struct BinaryTreeNode
    {
        int                   m_nValue;
        BinaryTreeNode*        m_pLeft;
        BinaryTreeNode*        m_pRight;
    };
    
    bool isSymmetrical(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2);
    
    bool isSymmetrical(BinaryTreeNode* pRoot)
    {
        return isSymmetrical(pRoot, pRoot);
    }
    
    bool isSymmetrical(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2)
    {
        if(pRoot1 == nullptr && pRoot2 == nullptr)
            return true;
    
        if(pRoot1 == nullptr || pRoot2 == nullptr)
            return false;
    
        if(pRoot1->m_nValue != pRoot2->m_nValue)
            return false;
    
        return isSymmetrical(pRoot1->m_pLeft, pRoot2->m_pRight)
            && isSymmetrical(pRoot1->m_pRight, pRoot2->m_pLeft);
    }
    

    摘抄资料:《剑指offer》

    相关文章

      网友评论

          本文标题:对称的二叉树

          本文链接:https://www.haomeiwen.com/subject/rstqtrtx.html