Flip Equivalent Binary Trees

Medium Topics Company Tags

A flip at a node exchanges its entire left and right subtrees. Return true if some sequence of flips can make the two binary trees identical, or false otherwise. You may flip any number of nodes, including none.

Flips change the ordering of children but preserve node values and parent-child relationships. Two empty trees are equivalent.

Each tree is encoded as a level-order array. After the root, each present node contributes left and right child entries in queue order. null marks a missing child, and trailing missing entries may be omitted. [] represents an empty tree.

Example 1:

Flip Equivalent Binary Trees, example 1: illustration of the example

Input: root1 = [8,3,6,1]
root2 = [8,6,3,null,null,null,1]

Output: true

Explanation: Flip the root to exchange the subtrees rooted at 3 and 6. Then flip node 3 so its child 1 moves from the left side to the right side. The first tree now matches the second.

Example 2:

Flip Equivalent Binary Trees, example 2: illustration of the example

Input: root1 = [8,3,6,1]
root2 = [8,3,6,null,null,1]

Output: false

Explanation: Node 1 is a child of node 3 in the first tree and of node 6 in the second. Flipping only swaps the two child positions of a node; it cannot change a child's parent, so these trees cannot match.

Example 3:

Flip Equivalent Binary Trees, example 3: illustration of the example

Input: root1 = []
root2 = []

Output: true

Explanation: Both trees are empty and already identical, so no flips are needed.

Constraints:

  • Each tree contains between 0 and 100 nodes.
  • 0 <= Node.val <= 99
  • Node values are unique within each tree.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.