AAlgoLoopSpaced repetition for LeetCode
MEDIUMTree / RecursionLeetCode ↗

Construct Binary Tree from Preorder and Inorder Traversal

The key idea

The first element of preorder is always the current subtree's root. Finding that root inside inorder splits the remaining values into the left subtree (left of it) and the right subtree (right of it). A hash map from value to its inorder index makes each split O(1).

Problem

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

The tree contains only unique values, and every value in one array appears in the other. Your job is to recover the exact shape of the original tree from these two orderings.

Constraints

Examples

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] Output: [3,9,20,null,null,15,7]
Input: preorder = [-1], inorder = [-1] Output: [-1]

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems