Construct BST from Preorder

MediumArrayTreeBinary Search TreeBinary Tree

Description

Given an array of integers preorder representing the preorder traversal of a BST, construct the tree and return its root.

Examples

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

Root 8, insert 5 (left), 1 (left of 5), 7 (right of 5), 10 (right of 8), 12 (right of 10).

Input:preorder = [4,2,1,3,6,5,7]
Output:[4,2,6,1,3,5,7]
Explanation:

Inserting the preorder values into a BST yields [4,2,6,1,3,5,7].

Input:preorder = [10,5,3,8,15]
Output:[10,5,15,3,8]
Explanation:

The preorder values form the BST [10,5,15,3,8].

Constraints

  • 1 ≤ preorder.length ≤ 100

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!