Skip to problem
←

Construct BST from Preorder Traversal

Hard 0 attempts

You're given an array preorder representing the preorder traversal of a binary search tree. Build that BST and return its root.

Function contract

Implement bstFromPreorder(preorder), where preorder is a valid root-left-right traversal of a BST with unique values.

Output: The root node of the BST, using val, left, and right fields. The runner displays it in level order, trimming trailing nulls.

Example 1

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

Example 2

Input
preorder = [1]
Output
[1]
Visual Aid
Restore the BST shape
85101712Preorder: 8, 5, 1, 7, 10, 12

Every left descendant is smaller than its ancestor and every right descendant is larger.

Constraints
  • 1 <= preorder.length <= 100
  • 1 <= preorder[i] <= 10^8
  • All values are unique
  • preorder is guaranteed to be a valid BST preorder traversal.

Recursive with Bound

Use an upper bound to determine when to stop building the left subtree.

javascript
function bstFromPreorder(preorder) {
  let i = 0;
  function build(bound) {
    if (i >= preorder.length || preorder[i] > bound) return null;
    const node = { val: preorder[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) recursion depth, O(n) for a skewed tree, excluding the returned tree.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript