Symmetric Tree Problem
Description
LeetCode Problem 101.
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
- The number of nodes in the tree is in the range [1, 1000].
- -100 <= Node.val <= 100
Solution
Approach: Recursive Mirror Check
A tree is symmetric when its left subtree is the mirror image of its right subtree. So the real question is: given two trees a and b, is b the mirror of a?
That holds when:
- both are empty, or
- both exist,
a.val == b.val, anda.leftmirrorsb.right(the two outer subtrees), anda.rightmirrorsb.left(the two inner subtrees).
If exactly one of a and b is empty, or their values differ, they are not mirrors. The answer is isMirror(root.left, root.right); the root always exists here because the tree has at least one node.
1
/ \
2 2 outer pair: 3 and 3
/ \ / \ inner pair: 4 and 4
3 4 4 3
The mistake to avoid is comparing a.left with b.left. That checks whether the two halves are equal copies, not mirror images. In [1,2,2,3,4,3,4] both halves are 2 with children 3, 4, yet the tree is not symmetric.
Complexity: O(n) time and O(h) extra space for the recursion, where n is the number of nodes and h is the height of the tree.
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def is_mirror(a: Optional[TreeNode], b: Optional[TreeNode]) -> bool:
"""True when tree b is the mirror image of tree a."""
if a is None and b is None:
return True
if a is None or b is None or a.val != b.val:
return False
# outer children pair up, and so do inner children
return is_mirror(a.left, b.right) and is_mirror(a.right, b.left)
return is_mirror(root.left, root.right)
Now write it from memory
Close the write-up and solve it yourself against the tests.