Flip Binary Tree To Match Preorder Traversal — LeetCode 971 Python Solution

MediumTreeDepth-First SearchBinary Tree
Problem
#971
Reading time
5 min

The 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.

Example

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.

Python solution

Python
# 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]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of nodes in the tree auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 971. Flip Binary Tree To Match Preorder Traversal is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 971. Flip Binary Tree To Match Preorder Traversal?
LeetCode 971. Flip Binary Tree To Match Preorder Traversal is rated Medium on LeetCode.
What is the time complexity of LeetCode 971. Flip Binary Tree To Match Preorder Traversal?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 971. Flip Binary Tree To Match Preorder Traversal?
The Python solution on this page uses O(n), where n is the number of nodes in the tree auxiliary space.
What topics does LeetCode 971. Flip Binary Tree To Match Preorder Traversal cover?
LeetCode 971. Flip Binary Tree To Match Preorder Traversal is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview