Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.
Move from brute-force thinking to an efficient approach using tree strategy.
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 have the following effect:
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].
Example 1:
Input: root = [1,2], voyage = [2,1] Output: [-1] Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage.
Example 2:
Input: root = [1,2,3], voyage = [1,3,2] Output: [1] Explanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.
Example 3:
Input: root = [1,2,3], voyage = [1,2,3] Output: [] Explanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.
Constraints:
n.n == voyage.length1 <= n <= 1001 <= Node.val, voyage[i] <= nvoyage are unique.Problem summary: 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 have the following effect: 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].
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Tree
[1,2] [2,1]
[1,2,3] [1,3,2]
[1,2,3] [1,2,3]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #971: Flip Binary Tree To Match Preorder Traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int i;
private boolean ok;
private int[] voyage;
private List<Integer> ans = new ArrayList<>();
public List<Integer> flipMatchVoyage(TreeNode root, int[] voyage) {
this.voyage = voyage;
ok = true;
dfs(root);
return ok ? ans : List.of(-1);
}
private void dfs(TreeNode root) {
if (root == null || !ok) {
return;
}
if (root.val != voyage[i]) {
ok = false;
return;
}
++i;
if (root.left == null || root.left.val == voyage[i]) {
dfs(root.left);
dfs(root.right);
} else {
ans.add(root.val);
dfs(root.right);
dfs(root.left);
}
}
}
// Accepted solution for LeetCode #971: Flip Binary Tree To Match Preorder Traversal
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func flipMatchVoyage(root *TreeNode, voyage []int) []int {
i := 0
ok := true
ans := []int{}
var dfs func(*TreeNode)
dfs = func(root *TreeNode) {
if root == nil || !ok {
return
}
if root.Val != voyage[i] {
ok = false
return
}
i++
if root.Left == nil || root.Left.Val == voyage[i] {
dfs(root.Left)
dfs(root.Right)
} else {
ans = append(ans, root.Val)
dfs(root.Right)
dfs(root.Left)
}
}
dfs(root)
if !ok {
return []int{-1}
}
return ans
}
# Accepted solution for LeetCode #971: Flip Binary Tree To Match Preorder Traversal
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:
def dfs(root):
nonlocal i, ok
if root is None or not ok:
return
if root.val != voyage[i]:
ok = False
return
i += 1
if root.left is None or root.left.val == voyage[i]:
dfs(root.left)
dfs(root.right)
else:
ans.append(root.val)
dfs(root.right)
dfs(root.left)
ans = []
i = 0
ok = True
dfs(root)
return ans if ok else [-1]
// Accepted solution for LeetCode #971: Flip Binary Tree To Match Preorder Traversal
struct Solution;
use rustgym_util::*;
trait Preorder {
fn preorder(&self, size: &mut usize, nodes: &mut Vec<i32>, voyage: &[i32]) -> bool;
}
impl Preorder for TreeLink {
fn preorder(&self, size: &mut usize, nodes: &mut Vec<i32>, voyage: &[i32]) -> bool {
if let Some(node) = self {
let node = node.borrow();
let val = node.val;
if voyage[*size] != val {
return false;
}
*size += 1;
if node.left.is_none() && node.right.is_none() {
return true;
}
if node.left.is_some() {
if node.left.as_ref().unwrap().borrow().val == voyage[*size] {
node.left.preorder(size, nodes, voyage)
&& node.right.preorder(size, nodes, voyage)
} else {
nodes.push(val);
node.right.preorder(size, nodes, voyage)
&& node.left.preorder(size, nodes, voyage)
}
} else {
node.right.preorder(size, nodes, voyage)
}
} else {
true
}
}
}
impl Solution {
fn flip_match_voyage(root: TreeLink, voyage: Vec<i32>) -> Vec<i32> {
let mut nodes = vec![];
let mut size: usize = 0;
if root.preorder(&mut size, &mut nodes, &voyage) {
nodes
} else {
vec![-1]
}
}
}
#[test]
fn test() {
let root = tree!(1, tree!(2), None);
let voyage = vec![2, 1];
let res = vec![-1];
assert_eq!(Solution::flip_match_voyage(root, voyage), res);
let root = tree!(1, tree!(2), tree!(3));
let voyage = vec![1, 3, 2];
let res = vec![1];
assert_eq!(Solution::flip_match_voyage(root, voyage), res);
let root = tree!(1, tree!(2), tree!(3));
let voyage = vec![1, 2, 3];
let res: Vec<i32> = vec![];
assert_eq!(Solution::flip_match_voyage(root, voyage), res);
}
// Accepted solution for LeetCode #971: Flip Binary Tree To Match Preorder Traversal
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function flipMatchVoyage(root: TreeNode | null, voyage: number[]): number[] {
let ok = true;
let i = 0;
const ans: number[] = [];
const dfs = (root: TreeNode | null): void => {
if (!root || !ok) {
return;
}
if (root.val !== voyage[i++]) {
ok = false;
return;
}
if (!root.left || root.left.val === voyage[i]) {
dfs(root.left);
dfs(root.right);
} else {
ans.push(root.val);
dfs(root.right);
dfs(root.left);
}
};
dfs(root);
return ok ? ans : [-1];
}
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.