sagelearnai

Symmetric Tree

Difficulty: Easy · Pattern: Trees & BST · LeetCode #101

Given the root of a binary tree, check whether it is a mirror of itself, meaning symmetric around its center.

Examples

text
        1                 1
      /   \             /   \
     2     2           2     2
    / \   / \           \     \
   3   4 4   3           3     3
   → true               → false

Hints

  1. A tree is symmetric when its left and right subtrees are mirror images of each other.
  2. Two trees a and b are mirrors when a.val == b.val, a.left mirrors b.right, and a.right mirrors b.left.

Approach

Write a helper mirror(a, b). It works like Same Tree, but the recursion crosses over:

  • mirror(a.left, b.right): the outer pair
  • mirror(a.right, b.left): the inner pair

The answer is mirror(root.left, root.right). An iterative BFS version puts the pairs in a queue in that crossed order.

Complexity

Time: O(n). Space: O(h).

Python solution
def isSymmetric(root):
    def mirror(a, b):
        if not a and not b:
            return True
        if not a or not b or a.val != b.val:
            return False
        return mirror(a.left, b.right) and mirror(a.right, b.left)
    return mirror(root.left, root.right) if root else True
JavaScript solution
function isSymmetric(root) {
  const mirror = (a, b) => {
    if (!a && !b) return true;
    if (!a || !b || a.val !== b.val) return false;
    return mirror(a.left, b.right) && mirror(a.right, b.left);
  };
  return root ? mirror(root.left, root.right) : true;
}