A flip operation on a binary tree chooses any node and swaps its left and right subtrees. Two binary trees are flip equivalent if one can be transformed into the other by performing some sequence of these flips (possibly none).
Given the roots root1 and root2 of two binary trees, return true if the trees 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
Flipping the subtree rooted at node 1's children, and then a nested flip lower down, turns the first tree into the second while keeping every value in place.
Example 2
Input: root1 = [], root2 = [1]
Output: false
An empty tree can never be made equal to a tree that contains a node, since flips never add or remove values.
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].See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI