A flip picks one node of a binary tree and swaps its left and right subtrees. Two trees are flip equivalent if some number of flips (possibly none) turns the first into the second.
Given root1 and root2, each the root of a binary tree, decide whether the two trees are flip equivalent.
Example 1
Input: root1 = [1, 2, 3, null, 4], root2 = [1, 3, 2, null, null, 4] Output: true Why: flip node 1, then flip node 2
2 more examples and the constraints
Example 2
Input: root1 = [5, 6, 7], root2 = [5, 6, 8] Output: false Why: flips never change values, and 7 is not 8
Example 3
Input: root1 = [], root2 = [0] Output: false Why: an empty tree cannot become one with a node
Constraints
- Each tree has between 0 and 100 nodes
- Within one tree every value is different, and 0 ≤ each value ≤ 99
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Write both trees in a fixed orderO(n)
- Recurse on both pairingsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two trees of 100 nodes | Verdict |
|---|---|---|---|
| Write in a fixed order | O(n) | Passes; builds two lists first | |
| Recurse on both pairings | O(n) | Best; no lists, stops early |
n = number of nodes, h = height of the tree.
Edge cases to test
- Both trees empty. Zero flips turn one empty tree into the other: true.
- One tree empty. [] and [0] differ. Check for empty before reading
.val. - Different values. Flips move subtrees but never change values, so any value mismatch means false.
- A leaf under a different parent. [1, 2, 3, 4] and [1, 2, 3, null, null, 4] hold the same values, but flips cannot move 4 from under 2 to under 3.
Common mistakes
- Trying only the crossed pairing, which says no when the trees are already identical.
- Deciding the pairing at the root and using it for every node, when each node may flip on its own.
- Reading
.valon an empty child before the null checks.
How to talk through it
- 1Clarify. Are values unique? Can either tree be empty? Is zero flips allowed?
- 2Name the cases. Both empty, one empty or different values, or try the two ways of pairing the children.
- 3Explain the cost. Unique values mean a wrong pairing fails at once, so the total work stays O(n).
- 4Offer the other view. Writing both trees with the smaller child first reduces it to comparing two lists.
- 5Test out loud. Run two empty trees, a full mirror image, and a leaf that sits under a different parent.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?