Skip to problem
←

Build a BST from Preorder

Medium 0 attempts

Given an array pre containing a valid preorder traversal of a binary search tree with distinct values, reconstruct that tree and return its root.

Preorder visits each node before its left subtree, then its right subtree. In this BST, every value in a node's left subtree is smaller and every value in its right subtree is larger. These rules determine one tree for the supplied traversal.

Create nodes with val, left, and right properties, using null for missing children. Return the root node, not an array. The editor displays the result in level order and trims trailing null entries.

For pre = [8, 5, 1, 7, 10, 12], the root is 8. Its left subtree has root 5 with children 1 and 7; its right subtree has root 10 with right child 12.

Function contract

Implement preorderToBST(pre).

Output: Return the result described in the statement. Returned trees are displayed as level-order arrays, trimming trailing nulls.

Example 1

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

Example 2

Input
pre = [1]
Output
[1]
Constraints
  • 1 <= N <= 10^3
  • 1 <= pre[i] <= 10^4
  • Values are distinct, and pre is guaranteed to be a valid preorder traversal of a strict BST.

Recursive Construction with an Upper Bound

Keep one shared index pointing to the next unused preorder value. build(bound) constructs the next subtree whose values must be below bound. If the next value exceeds the bound, it belongs to an ancestor's later subtree, so return null without consuming it.

Otherwise consume that value as a root. Build its left subtree with the root value as its upper bound, then build its right subtree with the inherited bound. This follows preorder's root-left-right order while consuming each value exactly once.

Distinct values and a guaranteed valid BST preorder are essential: they make an explicit lower-bound check unnecessary for reconstruction. This routine is not a validator for arbitrary traversal arrays.

javascript
function preorderToBST(pre) {
  let i = 0;
  function build(bound) {
    if (i >= pre.length || pre[i] > bound) return null;
    const node = { val: pre[i++], left: null, right: null };
    node.left = build(node.val);
    node.right = build(bound);
    return node;
  }
  return build(Infinity);
}

Time: O(n) | Space: O(h) auxiliary recursion space plus O(n) for the returned nodes, where h is the reconstructed tree height. A sorted traversal produces height n.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript