00:00

Problem Statement

Input/Output Examples

Visual Explanation

Because preorder lists a whole left subtree before the right subtree, building the left side first consumes exactly the right number of preorder values.

Approaches

Both approaches split the inorder range around each root. One finds the root's position with a map; the other searches for it.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of nodes. With the map, each node is created once with constant work; the scanning version can repeat linear searches for each node.

Interview Tips and Recommended Approach

  • Values must be unique; otherwise the root's inorder position is ambiguous.
  • Build the left subtree first when consuming preorder values.
  • Know the postorder version: take roots from the end of postorder and build the right subtree first.
  • Preorder plus postorder is not enough to rebuild a general binary tree uniquely.

Recommended Approach: Recursion With a Position Map

Why: it rebuilds the tree in linear time and makes the role of each traversal explicit.