LeetCode 题解工作台
对称二叉树
给你一个二叉树的根节点 root , 检查它是否轴对称。 示例 1: 输入: root = [1,2,2,3,4,4,3] 输出: true 示例 2: 输入: root = [1,2,2,null,3,null,3] 输出: false 提示: 树中节点数目在范围 [1, 1000] 内 -100…
4
题型
7
代码语言
3
相关题
当前训练重点
简单 · 二分·树·traversal
答案摘要
我们设计一个函数 $\textit{dfs}(\textit{root1}, \textit{root2})$,用于判断两个二叉树是否对称。答案即为 $\textit{dfs}(\textit{root.left}, \textit{root.right})$。 函数 $\textit{dfs}(\textit{root1}, \textit{root2})$ 的逻辑如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false
提示:
- 树中节点数目在范围
[1, 1000]内 -100 <= Node.val <= 100
进阶:你可以运用递归和迭代两种方法解决这个问题吗?
解题思路
方法一:递归
我们设计一个函数 ,用于判断两个二叉树是否对称。答案即为 。
函数 的逻辑如下:
- 如果 和 都为空,则两个二叉树对称,返回
true; - 如果 和 中只有一个为空,或者
- 否则,判断 的左子树和 的右子树是否对称,以及 的右子树和 的左子树是否对称,这里使用了递归。
时间复杂度 ,空间复杂度 。其中 是二叉树的节点数。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def dfs(root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
if root1 == root2:
return True
if root1 is None or root2 is None or root1.val != root2.val:
return False
return dfs(root1.left, root2.right) and dfs(root1.right, root2.left)
return dfs(root.left, root.right)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you account for null nodes when checking symmetry?
- question_mark
Can you implement both DFS and BFS approaches for mirrored comparison?
- question_mark
Will you detect asymmetry early to optimize traversal?
常见陷阱
外企场景- error
Forgetting to compare null nodes correctly, which causes incorrect true results.
- error
Swapping children in the wrong order during BFS, breaking the mirror logic.
- error
Assuming symmetric values without verifying mirrored positions across the tree.
进阶变体
外企场景- arrow_right_alt
Check if an N-ary tree is symmetric using similar mirrored comparisons.
- arrow_right_alt
Determine symmetry for a tree with additional parent pointers included.
- arrow_right_alt
Validate symmetry after inserting a new node dynamically and updating subtree reflections.