Flip Equivalent Binary Trees - Problem

Imagine you have two binary trees that look different, but could potentially be made identical by flipping some nodes. In a flip operation, you can choose any node and swap its left and right child subtrees.

Given the roots of two binary trees root1 and root2, determine if they are flip equivalent - meaning one can be transformed into the other through a series of flip operations.

Key Insight: Two trees are flip equivalent if at each corresponding node, the children match either in the same order OR in flipped order.

Goal: Return true if the trees are flip equivalent, false otherwise.

Input & Output

example_1.py โ€” Basic Flip Equivalence
$ Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]
โ€บ Output: true
๐Ÿ’ก Note: Tree1 can be made identical to Tree2 by flipping the children of node 1. After flipping, both trees have the same structure and values.
example_2.py โ€” Non-Equivalent Trees
$ Input: root1 = [1,2,3], root2 = [1,2,4]
โ€บ Output: false
๐Ÿ’ก Note: The trees cannot be made equivalent because they have different values (3 vs 4). No amount of flipping can change node values.
example_3.py โ€” Empty Trees
$ Input: root1 = [], root2 = []
โ€บ Output: true
๐Ÿ’ก Note: Two empty trees are always flip equivalent. This is our base case that returns true immediately.

Constraints

  • The number of nodes in each tree is in the range [0, 100]
  • Each tree will have unique node values in the range [0, 99]
  • Node values are integers

Visualization

Tap to expand
๐Ÿชž Mirror Maze EquivalenceMaze ARoom 1Room 2Room 3Maze BRoom 1Room 3Room 2โŒ Normal Path CheckLeft: Room2 โ‰  Room3Right: Room3 โ‰  Room2Paths don't match!โœ… Flipped Path CheckLeft: Room2 = Room2Right: Room3 = Room3Mirrors flipped work!๐ŸŽฏ Mazes are Equivalent! (After flipping mirrors in Room 1)
Understanding the Visualization
1
Enter Both Mazes
Start at the entrance of both mirror mazes simultaneously
2
Check Junction Values
At each junction, verify the room numbers match
3
Try Normal Path
Check if left-left and right-right paths work
4
Try Flipped Path
If normal doesn't work, try left-right and right-left
5
Declare Equivalence
If either orientation works for all paths, mazes are equivalent
Key Takeaway
๐ŸŽฏ Key Insight: Instead of physically flipping mirrors, we can mentally check both orientations at each junction. If either the normal path or the flipped path works throughout the entire maze, the mazes are equivalent!
Asked in
Google 42 Facebook 28 Amazon 21 Microsoft 15
98.2K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen