NeetCode #431LC-101EasyTrees
← Back to All Problems#431 · #101 · Symmetric Tree(对称二叉树)
📌 Problem Statement & Constraints
Given the root of a binary tree, check whether it is mirror-symmetric around its centre. Constraints: the number of nodes is in
[1, 1000], -100 <= Node.val <= 100.💡 Core Algorithmic Approaches
- Two subtrees are mirrors when their roots have equal values and the left of one mirrors the right of the other.
- So recurse on the pair
(a.left, b.right)and(a.right, b.left). - The base cases are both
None(symmetric) and exactly oneNone(not symmetric). - Starting the comparison at
(root.left, root.right)handles the whole tree.
💻 Benchmark Python3 Implementation
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def mirror(a: Optional[TreeNode], b: Optional[TreeNode]) -> bool:
if not a and not b:
return True
if not a or not b:
return False
return (a.val == b.val
and mirror(a.left, b.right) # cross pairing
and mirror(a.right, b.left))
return mirror(root.left, root.right) if root else True⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each pair of mirrored nodes is compared once.
💾 Space Complexity
O(h) for the recursion stack.
⚠️ Interview Pitfalls & Follow-ups
- Comparing
(a.left, b.left): that tests equality, not symmetry; the pairing must be crossed. - Forgetting the
exactly one Nonecase: it would dereferenceNone. - Serialising and comparing the string with its reverse: workable, but the null markers and delimiters must be right, and it uses O(n) space.
- Handling the empty tree: it is trivially symmetric.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Trees Problems
中文速览与面试要点
对称二叉树
给你一个二叉树的根节点 root,检查它是否轴对称。约束:树中节点数目在范围 [1, 1000] 内;-100 ≤ Node.val ≤ 100。
核心要点
- 递归镜像比较(标准解) :写一个辅助函数比较两个节点 a 、 b 是否互为镜像——要求 a.val == b.val 、 a.left 与 b.right 镜像、 a.right 与 b.left 镜像。
- 为什么是交叉比较 :轴对称意味着左子树的「左」对应右子树的「右」,因此必须交叉递归。
- 迭代方案 :用队列成对入队镜像节点,逐个比较。
- 复杂度 :O(n) 时间、O(h) 空间。
常见陷阱
- 用 isSameTree(root.left, root.right) :那是「相同」而非「镜像」,会得到错误结果。必须交叉比较。
- 只比较根的两个子节点值 :必须递归到所有层级。
- 忘记处理空树 :应返回 True。
- 「交叉比较」写成同侧比较 : mirror(a.left, b.left) 是判断「相同」,不是镜像。
参考实现
class Solution:
def isSymmetric(self, root: 'TreeNode') -> bool:
def mirror(a, b) -> bool:
if not a and not b:
return True
if not a or not b:
return False
return (a.val == b.val
and mirror(a.left, b.right) # 交叉比较
and mirror(a.right, b.left))
return mirror(root.left, root.right) if root else True