Flip Binary Tree To Match Preorder Traversal - Problem

You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree.

Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will swap its left and right children.

Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage. Return a list of the values of all flipped nodes. You may return the answer in any order.

If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage, return the list [-1].

Input & Output

Example 1 — Need to Flip Root
$ Input: root = [1,2], voyage = [1,2]
Output: []
💡 Note: Tree already matches voyage [1,2] with preorder traversal, no flips needed
Example 2 — Flip Required
$ Input: root = [1,2,3], voyage = [1,3,2]
Output: [1]
💡 Note: Original preorder is [1,2,3], but we need [1,3,2]. Flip node 1 to swap children 2 and 3
Example 3 — Impossible Case
$ Input: root = [1,2,3], voyage = [1,2,4]
Output: [-1]
💡 Note: Tree has node 3 but voyage expects node 4, which doesn't exist in tree

Constraints

  • The number of nodes in the tree is n
  • n == voyage.length
  • 1 ≤ n ≤ 100
  • 1 ≤ Node.val, voyage[i] ≤ n
  • All the values in the tree are unique
  • All the values in voyage are unique

Visualization

Tap to expand
Flip Binary Tree To Match Preorder Traversal123Original: [1,2,3]→ FLIP →Target: [1,3,2]132After Flip: [1,3,2]Output: [1]Node 1 was flipped to achieve target voyage
Understanding the Visualization
1
Input
Binary tree [1,2,3] and target voyage [1,3,2]
2
Process
Flip node 1 to swap its children
3
Output
Return [1] indicating which nodes were flipped
Key Takeaway
🎯 Key Insight: Compare preorder traversal with target and flip nodes when children don't match expected order
Asked in
Google 15 Amazon 8 Microsoft 5
32.4K Views
Medium Frequency
~25 min Avg. Time
856 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