Flip Equivalent Binary Trees
1 approach, code in every language
Problem description
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].
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free