Sponsored
Sponsored
The idea is to use a recursive approach that performs a pre-order traversal, comparing each visited node with the corresponding value in the voyage
sequence. If the current node's value doesn't match, it may be necessary to flip its children and recheck. The goal is to flip the minimum number of nodes such that the tree's pre-order traversal matches the given voyage
. If impossible, return [-1]
.
Time Complexity: O(n) since we traverse all nodes in the binary tree once.
Space Complexity: O(h) due to the recursion call stack, where h is the height of the tree.
1class Solution:
2 def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:
3 self.res, self.i = [], 0
4
5 def dfs(node):
6 if not node:
7 return True
8 if node.val != voyage[self.i]:
9 return False
10 self.i += 1
11 if (node.left and node.left.val != voyage[self.i]):
12 self.res.append(node.val)
13 return dfs(node.right) and dfs(node.left)
14 return dfs(node.left) and dfs(node.right)
15
16 return self.res if dfs(root) else [-1]
This solution uses a depth-first search (dfs) recursively to perform a pre-order traversal. First, iterate through the tree with dfs
, comparing each current node's value with voyage[i]
. If values match, increment the index. When a node is reached whose left child's value does not match the next required voyage
entry, flip its children. If no flips can result in an appropriate traversal, return [-1]. Store and return all nodes whose children were flipped.
This approach uses an explicit stack to simulate a pre-order traversal iteratively and checks against the voyage
. The stack helps process nodes similar to recursion, with flipping decisions based on discrepancies between expected and current values.
Time Complexity: O(n) since each node is processed once.
Space Complexity: O(h) where h is the height of the binary tree. The stack size is determined by the deepest path.
1import java.util.*;
2
This solution uses an iterative approach to traverse the tree pre-order using a stack. Nodes are pushed on the stack to be processed later. If the node's value doesn't match the current index in voyage
, we return [-1]
. If the right child's value equals the next entry in voyage
, consider flipping the children if a left child exists, and add the flipped node to res
. Push children in an order that aligns with the traversal aimed for by voyage
.