Construct Binary Search Tree from Preorder Traversal - Problem

Given an array of integers representing the preorder traversal of a Binary Search Tree (BST), your task is to reconstruct and return the original BST.

In a BST, for every node:

  • All values in the left subtree are strictly less than the node's value
  • All values in the right subtree are strictly greater than the node's value

A preorder traversal visits nodes in this order: root โ†’ left subtree โ†’ right subtree

Example: If preorder = [8, 5, 1, 7, 10, 12], this represents:

    8
   / \
  5   10
 / \   \
1   7   12

You need to reconstruct this tree structure and return the root node. It's guaranteed that a valid BST can always be constructed from the given preorder sequence.

Input & Output

example_1.py โ€” Standard BST
$ Input: preorder = [8,5,1,7,10,12]
โ€บ Output: [8,5,10,1,7,null,12]
๐Ÿ’ก Note: The preorder traversal represents a BST where 8 is root, 5 and 10 are children of 8, and so on. The output shows the tree in level-order format.
example_2.py โ€” Single Node
$ Input: preorder = [1]
โ€บ Output: [1]
๐Ÿ’ก Note: A tree with only one node - the root node with value 1.
example_3.py โ€” Right Skewed Tree
$ Input: preorder = [1,2,3,4]
โ€บ Output: [1,null,2,null,3,null,4]
๐Ÿ’ก Note: Since each value is greater than the previous, each node only has a right child, creating a right-skewed tree.

Constraints

  • 1 โ‰ค preorder.length โ‰ค 100
  • 1 โ‰ค preorder[i] โ‰ค 1000
  • All values in preorder are unique
  • The input represents a valid preorder traversal of a BST

Visualization

Tap to expand
BST Construction: Preorder [8, 5, 1, 7, 10, 12]8(-โˆž, +โˆž)5(-โˆž, 8)10(8, +โˆž)1712Processing StepsStep 1: Process 8 โ†’ Root (-โˆž, +โˆž)Step 2: Process 5 โ†’ 5 < 8, go leftStep 3: Process 1 โ†’ 1 < 5, go leftStep 4: Process 7 โ†’ 5 < 7 < 8, right of 5Step 5: Process 10 โ†’ 10 > 8, go rightStep 6: Process 12 โ†’ 12 > 10, right of 10Time: O(n) - Each node processed onceSpace: O(h) - Recursion stack height
Understanding the Visualization
1
Initialize Bounds
Start with root and infinite bounds (-โˆž, +โˆž)
2
Place Node
If current value fits bounds, create node and advance index
3
Update Bounds
Left child gets (min, current), right child gets (current, max)
4
Recurse
Continue with updated bounds for each subtree
Key Takeaway
๐ŸŽฏ Key Insight: Using bounds eliminates the need to scan for subtree boundaries. Each recursive call constrains valid values, allowing sequential processing of the preorder array in optimal O(n) time.
Asked in
Facebook 35 Amazon 28 Google 22 Microsoft 18
89.5K Views
Medium-High Frequency
~15 min Avg. Time
2.3K 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