Problem
Given theroot of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Examples
Constraints
- The number of nodes in the tree is in the range [1, 1000].
- -100 <= Node.val <= 100
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 101 with 16 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 101 # by problem number
lcpy gen -s symmetric_tree # by problem name
root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Input: root = [1,2,2,3,4,4,3]
Output: true
Input: root = [1,2,2,null,3,null,3]
Output: false
from leetcode_py import TreeNode
class Solution:
# Time: O(n) — each node visited once
# Space: O(h) recursion stack, h = tree height
def is_symmetric(self, root: TreeNode[int] | None) -> bool:
def mirror(a: TreeNode[int] | None, b: TreeNode[int] | None) -> bool:
if a is None or b is None:
return a is b
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
| Time | Space |
|---|---|
| O(n) — each node visited once | O(h) recursion stack, h = tree height |