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 Traversal INPUT Binary Tree: 1 2 null Voyage (Target Preorder): 1 2 idx: 0 idx: 1 root=[1,2], voyage=[1,2] ALGORITHM STEPS 1 DFS Start Visit root, check node.val matches voyage[0]=1? OK 2 Check Left Child Left child=2, voyage[1]=2 Match! No flip needed 3 Traverse Left DFS on node 2 No children, return 4 Complete DFS All nodes matched No flips recorded DFS Traversal: Visit 1 --> Visit 2 Preorder: [1, 2] = voyage Flips needed: 0 FINAL RESULT Tree (No Changes): 1 2 Preorder Comparison: [1, 2] Tree Order = [1, 2] Voyage Output: [] No flips required! Key Insight: During DFS, if left child doesn't match next voyage value, flip the node (swap left/right). If after potential flip, values still don't match, return [-1]. Track flipped node values in result list. TutorialsPoint - Flip Binary Tree To Match Preorder Traversal | DFS with Backtracking
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