Python coding

Rebuild a tree from its traversals

Write rebuild(preorder, inorder): the two lists are walks of the same binary tree, whose values are all distinct. preorder lists each node before its left subtree and then its right subtree; inorder lists the left subtree, then the node, then the right subtree. Rebuild that tree and return its root; two empty lists mean an empty tree. Each TreeNode has val, left and right.

The tests call the provided run_rebuild(preorder, inorder), which returns your tree level by level with null for a missing child: [1, null, 2, 3] is a root 1 with only a right child 2, whose left child is 3.

Aim for O(n).

  • run_rebuild([3,9,20,15,7], [9,3,15,20,7]) → [3,9,20,null,null,15,7]
  • run_rebuild([1,2,3], [3,2,1]) → [1,2,null,3]
  • run_rebuild([], []) → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

The first value of preorder is the root. Find it in inorder: everything to its left is the left subtree, everything to its right is the right subtree.

Hint 2

Recurse on a range of inorder and take roots from preorder in order, building the left subtree before the right: preorder lists the whole left subtree first.

Hint 3

inorder.index(...) and slicing cost O(n) per node, O(n²) on a lopsided tree. A dict from value to inorder position makes each split O(1).

Solution and why it works
pythonO(n) · O(n) for the index map, plus O(h) stack
# --- your code ---
def rebuild(preorder: list[int], inorder: list[int]) -> "TreeNode | None":
    where = {val: i for i, val in enumerate(inorder)}
    roots = iter(preorder)                # preorder hands out each subtree's root in turn

    def build(lo: int, hi: int) -> "TreeNode | None":
        """The subtree whose inorder walk is inorder[lo:hi]."""
        if lo == hi:
            return None
        node = TreeNode(next(roots))
        mid = where[node.val]
        node.left = build(lo, mid)        # the whole left subtree comes next in preorder
        node.right = build(mid + 1, hi)
        return node

    return build(0, len(inorder))


# --- provided: do not edit ---
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def build_tree(values: list[int | None]) -> TreeNode | None:
    # Level order: each existing node takes the next two entries as its left and right child.
    nodes = [None if v is None else TreeNode(v) for v in values]
    children = iter(nodes[1:])
    for node in nodes:
        if node is not None:
            node.left = next(children, None)
            node.right = next(children, None)
    return nodes[0] if nodes else None


def to_values(root: TreeNode | None, limit: int) -> list[int | None]:
    # The inverse of build_tree: level order, None for a missing child, no trailing None.
    out, queue, count = [], [root], 0
    for node in queue:                    # the list grows while we walk it: a BFS queue
        if node is None:
            out.append(None)
            continue
        count += 1
        if count > limit:
            raise ValueError("the result has more nodes than the input: is a node linked twice?")
        out.append(node.val)
        queue += [node.left, node.right]
    while out and out[-1] is None:
        out.pop()
    return out


def run_rebuild(preorder: list[int], inorder: list[int]) -> list[int | None]:
    return to_values(rebuild(preorder, inorder), len(preorder))

Preorder names the root first; inorder places it between its two subtrees, so its position tells how many nodes go left. A dict from value to inorder index makes each split O(1), and an iterator over preorder hands out roots in the exact order of a preorder build: node, whole left subtree, right subtree. So build left before right. Each node is created once: O(n). The trap is inorder.index plus slicing, O(n²) on a lopsided tree. Duplicate values would make the split ambiguous, hence the distinct values.