【面试题】判断一颗二叉树是不是对称的

对称二叉树符合的条件:

根节点以及其左右子树
左子树的左子树和右子树的右子树相同
左子树的右子树和右子树的左子树
即判断其与其的镜像是否相同。

class Solution {
public:
    bool isSymmetrical(TreeNode* pRoot)
    {
       if(pRoot==NULL)
            return true;
       return IsMirror(pRoot->left,pRoot->right);
    }
    bool IsMirror(TreeNode *pLeft,TreeNode *pRight)
    {
        if(pLeft==NULL&&pRight==NULL)
            return true;
        if(pLeft==NULL||pRight==NULL)
            return false;
        if(pLeft->val!=pRight->val)
            return false;
        return (IsMirror(pLeft->left,pRight->right))&&(IsMirror(pLeft->right,pRight->left));
    }

};

猜你喜欢

转载自blog.csdn.net/mmwwxx123/article/details/81774851