Leetcode101. 对称二叉树 -hot100-代码随想录

题目:


代码(首刷看解析 2024年1月25日):

class Solution {
public:
    bool recursion(TreeNode* left, TreeNode* right) {
        if (left && !right) return false;
        else if (!left && right) return false;
        else if (!left && !right) return true;
        else if (left && right && left->val != right->val) return false;
        
        bool out = recursion(left->left,right->right);
        bool in  = recursion(left->right,right->left);
        bool access = out && in;
        return access;
    }
    bool isSymmetric(TreeNode* root) {
        if (root == nullptr) return true;
        return recursion(root->left,root->right);
    }
};

代码(二刷看解析 2024年3月5日)

class Solution {
public:
    bool check(TreeNode* left, TreeNode* right) {
        if (!(left || right)) return true;
        else if (!(left && right) || left->val != right->val) return false;
        bool out = check(left->left, right->right);
        bool in = check(left->right, right->left);
        return out && in;
    }
    bool isSymmetric(TreeNode* root) {
        if (!root) return true;
        return check(root->left, root->right);
    }
};

代码(三刷看解析 2024年5月8日)

好好好,在一道easy题上折戟三次;这道题加入重点关照库,不刷十次不算完。

class Solution {
public:
    bool compare(TreeNode* left, TreeNode* right) {
        // 处理存在空节点的情况
        if (!left && right) return false;
        else if (left && !right) return false;
        else if (!left && !right) return true;
        else if (left->val != right->val) return false;

        // 处理单层逻辑,需要用后序遍历。对比外侧和内测
        bool outside = compare(left->left, right->right);
        bool inside = compare(left->right, right->left);
        bool isSame = outside && inside;
        return isSame;
    }
    bool isSymmetric(TreeNode* root) {
        if (!root) return true;
        return compare(root->left, root->right);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值