Binary Search Trees Using the ordering
392. Construct Binary Search Tree from Preorder Traversal
You are given an integer array preorder. It is the preorder traversal of a binary search tree whose values are
all distinct. Build that tree and return its root.
A binary search tree (BST) keeps its values in order. For every node, every value in its left subtree is smaller than the node's value, and every value in its right subtree is larger. A preorder traversal lists a node, then its left subtree in preorder, then its right subtree in preorder.
The output shows the tree you return level by level, from left to right, with null where a child is missing.
So [5,3,null,1] is the root 5 with a left child 3 and no right child, and 3 has a left child 1. The missing
children after the last node are left out.
Example 1
Input: preorder = [40, 25, 10, 32, 28, 60, 75]
[40,25,60,10,32,null,75,null,null,28]Explanation: 40 comes first, so it is the root. The values smaller than 40 (25, 10, 32, 28) form its left subtree, with 25 on top, and 60 and 75 form its right subtree. Inside the left subtree, 10 goes left of 25, and 32 goes right, with 28 on its left.
Example 2
Input: preorder = [-1000000000, 1000000000, 0]
[-1000000000,null,1000000000,0]Explanation: The root is the smallest value, so it has no left child. 109 is its right child, and 0 lies between the two, so it is the left child of 109.
Example 3
Input: preorder = [2, 5, 9, 14]
[2,null,5,null,9,null,14]Explanation: Each value is larger than every value before it, so each one is the right child of the one before. The tree is a single path.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ preorder.length ≤ 105-109 ≤ preorder[i] ≤ 109- All the values are distinct.
preorderis the preorder traversal of a binary search tree.- The tree has at most 1000 levels.
Clarifying questions
What you would ask an interviewer before writing any code.