给你一个二叉树的根节点
root, 检查它是否轴对称。示例 1:
输入:root = [1,2,2,3,4,4,3]输出:true
核心思路
- 对比左子树和右子树
- 对称规则:
- 左节点值 = 右节点值
- 左孩子左分支 ↔ 右孩子右分支
- 左孩子右分支 ↔ 右孩子左分支
- 终止条件:双双为空对称,单一为空不对称
class Solution: def isSymmetric(self, root: Optional[TreeNode]) -> bool: def check(l, r): if not l and not r: return True if not l or not r: return False return l.val == r.val and check(l.left, r.right) and check(l.right, r.left) return check(root.left, root.right)