Problem 403937 · medium · Phase 04 Non-Linear Data Structures

Mirror-Symmetric Tree

binary trees · recursion · mirror comparison

Given the root of a binary tree, return True if the tree is a mirror of itself around a vertical line through the root: the left subtree must be the mirror image of the right subtree.

Examples

      1
     / \
    2   2
   / \ / \
  3  4 4  3

Input:  root = build_tree([1, 2, 2, 3, 4, 4, 3])
Output: True
    1
   / \
  2   2
   \   \
    3   3

Input:  root = build_tree([1, 2, 2, None, 3, None, 3])
Output: False

Constraints

  • 0 <= number of nodes <= 2000
  • -10**4 <= node.val <= 10**4
  • Target complexity: O(n) time.

Goals

  • Compare two subtrees as mirror images
  • Pair left-with-right and right-with-left in the recursion
  • Handle an empty tree and a single node
Starting Python…