题解 | #对称的二叉树#

对称的二叉树

https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb

/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 *  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类
     * @return bool布尔型
     */
    bool isSymmetrical(TreeNode* pRoot) {
        // write code here
        if (pRoot==nullptr)return true;
        return isMirror(pRoot->left, pRoot->right);
    }

    bool isMirror(TreeNode* r, TreeNode* l) {
        if (r==nullptr && l==nullptr) return true;
        if(r==nullptr ^ l==nullptr) return false;
        if (r->val != l->val)return false;
        return isMirror(r->left, l->right) && isMirror(r->right, l->left);
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务