#105

Construct Binary Tree from Preorder and Inorder Traversal

Medium Divide by root position

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Rebuild a binary tree (with unique values) from its preorder and inorder traversals.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: rebuild the tree from two traversals.

Why this works: preorder gives the root first; in inorder everything left of the root is the left subtree.

Example: pre [3, 9, 20, 15, 7], in [9, 3, 15, 20, 7]

root 3; left {9}; right {15, 20, 7}next root 20 → left 15, right 7

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Building the right subtree before the left — preorder lists the left subtree first.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Binary Trees
🎬 Episodes 53–60: video coming soon