Construct Binary Search Tree from Preorder Traversal

Given an array of distinct integers that is the preorder traversal of a binary search tree, construct the tree and return its root. In a BST, every node in the left subtree is smaller than the node and every node in the right subtree is larger. Preorder visits a node, then its left subtree, then its right subtree.

30:00

Construct Binary Search Tree from Preorder Traversal
medium
Free written solution
Topics
Companies

Given an array of distinct integers that is the preorder traversal of a binary search tree, construct the tree and return its root. In a BST, every node in the left subtree is smaller than the node and every node in the right subtree is larger. Preorder visits a node, then its left subtree, then its right subtree.

Example 1:
Input: {"preorder":[8,5,1,7,10,12]}
Output: [8,5,10,1,7,null,12]
Constraints:
  • 1≤1 \le preorder.length ≤100\le 100

  • 1≤1 \le preorder[i] ≤1000\le 1000

  • All the values of preorder are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"preorder":[8,5,1,7,10,12]}

Read the preorder array left to right with one pointer i. Each call build(bound) may only take values below its bound; the first call has no bound.

8

i

5

i

1

i

7

i

10

i

12

i

calls (innermost first)

none

preorder[i] / new node
placed
slot the current call fills
value too big for this slot
Variables
VariableValue
i0
preorder[i]8
bound-
depth0
DepthFunction Call
Stack empty
0/37