CodingNodes / Trees / Construct Binary Tree From Preorder And Inorder Traversal System design Space play · ←→ step · R restart

Problem

You are given two arrays that describe the same binary tree: preorder, where every node comes before its subtrees (root, left, right), and inorder, where the left subtree comes first, then the node, then the right subtree. All values are distinct.

Rebuild the tree and return its root. Trees are written in level order, with null for a missing child.

Constraints

  • 1 ≤ n ≤ 3000
  • preorder and inorder both hold the same n distinct values
  • -3000 ≤ value ≤ 3000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: The map is built in one pass, and then each of the n nodes is created once, with a constant-time lookup to find its root.

Space: The map holds n entries, and the recursion goes as deep as the tree is tall, up to n for a chain.

The first value of any preorder part is that subtree's root. Find the root in inorder: everything before it is the left subtree and everything after it is the right subtree. The left size tells where the right subtree's preorder part begins, right after the left part. A map from value to inorder index makes each lookup instant.