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 Traversal INPUT Preorder Array: 8 5 1 7 10 12 0 1 2 3 4 5 Preorder: Root - Left - Right First element (8) is always root Left subtree: values < 8 BST Property: Left child < Parent Right child > Parent [8, 5, 1, 7, 10, 12] Guaranteed valid BST preorder ALGORITHM STEPS 1 Initialize with bounds Set min=-INF, max=+INF 2 Process preorder[i] Check if val in (min, max) 3 Create node, update bounds Left: (min, val), Right: (val, max) 4 Recurse for children Build left, then right subtree Build Process: i=0: 8 in (-INF,+INF) OK root i=1: 5 in (-INF,8) OK left i=2: 1 in (-INF,5) OK left.left i=3: 7 in (5,8) OK left.right i=4: 10 in (8,+INF) OK right i=5: 12 in (10,+INF) OK right.right Time: O(n) | Space: O(n) Single pass through array FINAL RESULT Constructed Binary Search Tree: 8 5 10 1 7 12 BST Property Verified Output (Level Order): [8,5,10,1,7,null,12] OK - Valid BST Key Insight: The upper bound approach uses BST property to determine valid placement. Each recursive call narrows the valid range: left subtree gets (min, node.val), right gets (node.val, max). This allows O(n) single-pass construction by processing elements in preorder sequence while maintaining BST constraints. TutorialsPoint - Construct Binary Search Tree from Preorder Traversal | Optimal Solution (Upper Bound Approach)
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