Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.
Example 1
Input: preorder = [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]
Explanation: 8 is the root. The next values smaller than 8 (5, 1, 7) form the left subtree: 5 with left child 1 and right child 7. The values larger than 8 (10, 12) form the right subtree: 10 with right child 12.
Example 2
Input: preorder = [1,3]
Output: [1,null,3]
Explanation: 1 is the root, and 3 is larger, so it becomes 1's right child.
Example 3
Input: preorder = [5]
Output: [5]
Explanation: A single value becomes a one-node tree.
In a preorder BST stream, each value either becomes the left child of the previous node (if smaller) or the right child of the nearest ancestor it is still larger than. A decreasing stack tracks candidate parents.
Run checks all cases above. Submit evaluates all test cases.