Skip to main content

Construct Binary Search Tree from Preorder Traversal - Solution & Explanation

MediumArrayStackTreeBinary Search Tree22 min readAsked at: Amazon, Microsoft, Meta +2
Practice this problem

Problem Statement

Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.

It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.

A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.

A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.

 

Example 1:

Input: preorder = [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

Example 2:

Input: preorder = [1,3]
Output: [1,null,3]

 

Constraints:

  • 1 <= preorder.length <= 100
  • 1 <= preorder[i] <= 1000
  • All the values of preorder are unique.

Approach Overview

Problem Overview: Given an array representing the preorder traversal of a Binary Search Tree, reconstruct the original BST and return its root. The preorder order guarantees that every node appears before its left and right subtree, while BST rules ensure left < root < right.

Approach 1: Recursive Insertion (Time: O(n^2), Space: O(h))

This approach builds the tree the same way values would be inserted into a normal BST. Iterate through the preorder array and insert each value into the tree using a recursive BST insert routine. For every insertion, traverse left or right depending on the value comparison until you find the correct position. The logic is simple and mirrors standard BST operations, which makes it easy to implement during interviews. The drawback is performance: if the preorder array is sorted, the BST becomes skewed and each insertion scans most of the tree, resulting in O(n^2) time.

Approach 2: Stack-based Iterative Construction (Time: O(n), Space: O(n))

This optimized method uses a stack to track the path of nodes whose right child hasn't been assigned yet. Start by creating the root from the first preorder value and push it onto the stack. For each next value, check the top of the stack. If the value is smaller, it becomes the left child of the top node. If the value is larger, pop nodes until you find the correct parent where the value should be attached as the right child. The stack maintains a decreasing sequence of ancestors, similar to a monotonic stack. Each element is pushed and popped at most once, giving O(n) time complexity.

The key insight comes from preorder traversal properties: nodes appear in root-left-right order, so once you encounter a value greater than a node, you've finished that node's left subtree and are moving to the right subtree. The stack efficiently tracks this transition.

Recommended for interviews: Interviewers typically expect the O(n) stack solution because it demonstrates understanding of preorder traversal constraints and Binary Search Tree structure. The recursive insertion approach still helps show baseline reasoning and correctness before optimizing.

Approach 1: Approach 1: Recursive Insertion

In this approach, you will construct the binary search tree (BST) by recursively inserting nodes. The property of the BST is used where, for each node, nodes in the left subtree are less, and nodes in the right subtree are greater.

Start with the first element from the preorder sequence, which will be the root. Recursively insert subsequent elements using the BST insertion logic, and this will ensure that the tree constructed respects both the structure of a BST and adheres to the given preorder traversal.

This C solution recursively inserts each element of the preorder array into the BST using standard recursive insertion. Starting with the first element as the root, it iteratively adds each subsequent element by comparing values and guiding the insertion either to the left or the right subtree appropriately.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^2) in the worst case due to skewed trees where each insertion is O(n).
Space Complexity: O(n) due to the recursion stack and additional space for the BST nodes.

Try this approach in the editor →

Approach 2: Approach 2: Stack-based Iterative Construction

This approach uses a stack to iteratively construct the BST from the preorder traversal, which helps in achieving better average performance. Begin with the root node from the first preorder element, and iterate over the rest of the array with a technique to adjust parents as potential ancestors using a stack. Primary benefit is an average O(n log n) time complexity due to more constant-time parent-backtracking via stack use.

This C implementation uses an auxiliary stack structure to iteratively build the BST. By iterating over the preorder list, it appends each node either as a left child (when smaller) or as a right child using the stack to backtrack dynamically to suitable parent nodes.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), processing each node in a single pass with constant-time stack operations.
Space Complexity: O(n) due to the usage of an explicit stack for nodes.

Try this approach in the editor →

Approach 3: DFS + Binary Search

We design a function dfs(i, j) to construct a binary search tree from the nodes preorder[i] to preorder[j]. The answer is dfs(0, n - 1).

In dfs(i, j), we first construct the root node, which is preorder[i]. Then, we use binary search to find the first node greater than preorder[i] and get its index mid. We set dfs(i + 1, mid - 1) as the left subtree of the root node and dfs(mid, j) as the right subtree of the root node.

Finally, we return the root node.

The time complexity is O(n times log n), and the space complexity is O(n). Here, n is the length of the array preorder.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Approach 1: Recursive Insertion

Time Complexity: O(n^2) in the worst case due to skewed trees where each insertion is O(n).
Space Complexity: O(n) due to the recursion stack and additional space for the BST nodes.

Approach 2: Stack-based Iterative Construction

Time Complexity: O(n), processing each node in a single pass with constant-time stack operations.
Space Complexity: O(n) due to the usage of an explicit stack for nodes.

DFS + Binary Search—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive InsertionO(n^2) worst caseO(h)Simple implementation when demonstrating BST insertion logic
Stack-based Iterative ConstructionO(n)O(n)Optimal solution for large inputs and interview expectations

Video Solution

Construct binary search tree from preorder traversal | Leetcode #1008 • Techdose • 60,961 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Construct Binary Search Tree from Preorder Traversal easy or hard?
This problem is generally classified as Medium difficulty. The recursive insertion approach is straightforward, but identifying the O(n) stack optimization requires understanding preorder traversal properties and BST constraints.
Construct Binary Search Tree from Preorder Traversal Python/Java solution
Most solutions implement either recursive BST insertion or the stack-based iterative approach. Python and Java versions typically create nodes while scanning the preorder list and maintain a stack to assign left or right children. The stack method runs in O(n) time and is the preferred implementation in interviews.
How to solve Construct Binary Search Tree from Preorder Traversal in O(n)?
Use a stack to track nodes whose right subtree has not yet been constructed. Start with the first value as the root and push it to the stack. For each next value, attach it as the left child if it is smaller than the stack top; otherwise pop nodes until you find the correct parent and attach it as the right child. Each node is handled once, giving O(n) time.
What is the best approach for Construct Binary Search Tree from Preorder Traversal?
The optimal approach uses a stack to construct the BST in O(n) time. By processing preorder values sequentially and maintaining a stack of ancestors, you can determine whether the next value is a left child or the right child of a previously visited node. Each element is pushed and popped at most once, making it linear time.
Is Construct Binary Search Tree from Preorder Traversal asked at Google/Amazon/Meta?
Binary Search Tree reconstruction problems appear frequently in interviews at companies like Amazon, Google, and Meta. Variants include building a BST from preorder, validating BST properties, or reconstructing trees from traversal orders. The stack-based linear solution demonstrates strong understanding of tree traversal patterns.
What data structure is used in Construct Binary Search Tree from Preorder Traversal?
The problem primarily uses a Binary Search Tree structure combined with a stack for the optimal algorithm. The stack tracks the chain of ancestor nodes while processing preorder values. This allows efficient detection of transitions between left and right subtrees.
What is the time complexity of Construct Binary Search Tree from Preorder Traversal?
The optimal stack-based solution runs in O(n) time because each preorder value is processed once. A simpler recursive insertion approach may degrade to O(n^2) in the worst case when the tree becomes skewed. Space complexity ranges from O(h) for recursion depth to O(n) when using an explicit stack.

Ready to solve this problem?

Practice Construct Binary Search Tree from Preorder Traversal with our built-in code editor and test cases.

Practice on FleetCode