MediumNo. 0105

Construct Binary Tree from Preorder and Inorder Traversal — LeetCode 105 Python Solution

Topics
Tree, Array, Hash Table, Divide and Conquer, Binary Tree
Reading time
3 min

The problem

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

Example

Input
preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output
[3,9,20,null,null,15,7]

Python solution

PythonSolution
# 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 buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        def dfs(i: int, j: int, n: int) -> Optional[TreeNode]:
            if n <= 0:
                return None
            v = preorder[i]
            k = d[v]
            l = dfs(i + 1, j, k - j)
            r = dfs(i + 1 + k - j, k + 1, n - k + j - 1)
            return TreeNode(v, l, r)

        d = {v: i for i, v in enumerate(inorder)}
        return dfs(0, 0, len(preorder))

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 105. Construct Binary Tree from Preorder and Inorder 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 105. Construct Binary Tree from Preorder and Inorder Traversal?

LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal is rated Medium on LeetCode.

What is the time complexity of LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal cover?

LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal is tagged Tree, Array, Hash Table, Divide and Conquer 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.

Free to download. Check it runs on your machine, then pick a plan.