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

The Butterfly Fold Test

binary trees · recursion · mirror comparison

Fold a binary tree along a vertical line through its root, like the wings of a butterfly. It passes the fold test when the two halves land exactly on each other: the left subtree is the mirror image of the right subtree, in shape and in values. Given the root, return True if it passes.

Examples

      6
     / \
    4   4
   / \ / \
  2  9 9  2

Input:  root = build_tree([6, 4, 4, 2, 9, 9, 2])
Output: True
    6
   / \
  4   4
   \   \
    5   5

Input:  root = build_tree([6, 4, 4, None, 5, None, 5])
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…