Construct Binary Tree from Inorder and Postorder Traversal — LeetCode 106 Python Solution

MediumTreeArrayHash TableDivide and ConquerBinary Tree
Problem
#106
Reading time
3 min

The problem

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

Example

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

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

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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

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

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal?
LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal is rated Medium on LeetCode.
What is the time complexity of LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal cover?
LeetCode 106. Construct Binary Tree from Inorder and Postorder 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.

Get Stealth Interview