Construct Binary Tree from Preorder and Inorder Traversal
Problem Statement
You are given two arrays that describe the same binary tree.
preorder lists the nodes in preorder: the node, then its left subtree, then its right subtree. inorder lists the nodes in inorder: the left subtree, then the node, then the right subtree.
Rebuild the tree and return its root. All values in the tree are unique.
Two integer arrays, preorder and inorder, of the same length. They come from the same tree, and all values are unique.
The root of the tree that both arrays describe.
The first preorder value, 3, is the root. In inorder, the values left of 3 (just 9) form its left subtree. The values right of it (15, 20, 7) form its right subtree, and that subtree's root is the next preorder value, 20.
A tree with one node.
- • 1 ≤ preorder.length ≤ 3000
- • inorder.length == preorder.length
- • −3000 ≤ preorder[i], inorder[i] ≤ 3000
- • preorder and inorder consist of unique values.
- • Each value of inorder also appears in preorder.
- • preorder is guaranteed to be the preorder traversal of the tree.
- • inorder is guaranteed to be the inorder traversal of the tree.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Take the next preorder value as the root, then search inorder for it with a linear scan
Store each value's inorder index in a map once; take roots from preorder in order
Keep an index into preorder and an inorder range [lo..hi]. Take the next preorder value as the root, find it in the inorder range with a linear scan, and use its position to split the range. Build the left part and the right part the same way.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.