Flip Equivalent Binary Trees

A flip operation picks any node of a binary tree and swaps its left and right child subtrees. Two trees are flip equivalent when some number of flips turns the first tree into the second. Given the roots of two binary trees whose values are all unique, return true if they are flip equivalent and false otherwise.

30:00

Flip Equivalent Binary Trees
medium
Free written solution
Topics
Companies

A flip operation picks any node of a binary tree and swaps its left and right child subtrees. Two trees are flip equivalent when some number of flips turns the first tree into the second. Given the roots of two binary trees whose values are all unique, return true if they are flip equivalent and false otherwise.

Example 1:
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
Constraints:
  • The number of nodes in each tree is in the range [0,100][0, 100].

  • Each tree has unique node values in the range [0,99][0, 99].

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"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]}

Start with the two roots. Walk both trees together, pairing nodes that must match.

root1

12345678

root2

13264587

call stack

empty

current pairon the stackproven equal⇄ children matched crosswise

pairs proven: 0 • flips: 0

Variables
VariableValue
root1-
root2-
depth0
flips0
DepthFunction Call
Stack empty
0/40