#971

Flip Binary Tree To Match Preorder Traversal

Medium
TreeDepth-First SearchBinary TreeDepth-First SearchTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses depth-first search (DFS) to traverse the tree while checking against the voyage. It flips nodes only when necessary, ensuring a linear traversal of the tree.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty list for flips and set index to 0.
  2. 2Step 2: Perform a DFS traversal of the tree, comparing each node's value with the current value in the voyage.
  3. 3Step 3: If the left child exists but does not match the voyage, flip the node and continue the traversal.
solution.py25 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8class Solution:
9    def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:
10        flips = []
11        index = 0
12
13        def dfs(node):
14            nonlocal index
15            if not node:
16                return True
17            if node.val != voyage[index]:
18                return False
19            index += 1
20            if (node.left and index < len(voyage) and node.left.val != voyage[index]):
21                flips.append(node.val)
22                return dfs(node.right) and dfs(node.left)
23            return dfs(node.left) and dfs(node.right)
24
25        return flips if dfs(root) else [-1]

Complexity note: The time complexity is O(n) because we traverse each node exactly once. The space complexity is O(n) due to the recursion stack in the DFS.

  • 1Flipping nodes is necessary only when the left child does not match the expected value in the voyage.
  • 2DFS is an effective way to traverse the tree while keeping track of the required order.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.