Construct Binary Search Tree from Preorder Traversal - Problem

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.

Input & Output

Example 1 — Basic BST
$ Input: preorder = [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]
💡 Note: Preorder traversal visits root first (8), then left subtree (5,1,7), then right subtree (10,12). Reconstructed tree maintains BST property.
Example 2 — Single Node
$ Input: preorder = [1]
Output: [1]
💡 Note: Single node forms a tree with just the root.
Example 3 — Right Skewed Tree
$ Input: preorder = [1,3,5,7]
Output: [1,null,3,null,5,null,7]
💡 Note: Each node only has a right child, forming a right-skewed tree.

Constraints

  • 1 ≤ preorder.length ≤ 100
  • 1 ≤ preorder[i] ≤ 108
  • The values of preorder are unique

Visualization

Tap to expand
Construct BST from Preorder: [8,5,1,7,10,12] → TreeInput: [8, 5, 1, 7, 10, 12]⬇ Construct BST ⬇85101712Output: [8,5,10,1,7,null,12]
Understanding the Visualization
1
Input Array
Preorder traversal: [8,5,1,7,10,12]
2
BST Construction
Build tree following BST properties
3
Level-order Output
Return array representation: [8,5,10,1,7,null,12]
Key Takeaway
🎯 Key Insight: Use BST property constraints or monotonic stack to efficiently place each node in correct position
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
187.0K Views
Medium Frequency
~25 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen