SDE & MLE Prep

106. Construct Binary Tree from Inorder and Postorder Traversal

Problem

Rebuild a binary tree from its inorder and postorder traversals (all values are unique) and return the root.

Example: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] → [3,9,20,null,null,15,7]

Mirror of 105: the last postorder element is the root. Consume postorder from the end and build the right subtree first.

Complexity: O(n).

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        pos = {v: i for i, v in enumerate(inorder)}

        def build(lo, hi):
            if lo >= hi:
                return None
            root = TreeNode(postorder.pop())
            m = pos[root.val]
            root.right = build(m + 1, hi)
            root.left = build(lo, m)
            return root

        return build(0, len(inorder))