题目:
代码(首刷看解析 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);
}
};