You are given an integer array preorder, which represents the preorder traversal of a Binary Search Tree (BST). Your task is to reconstruct the BST and return its root.
It is guaranteed that the provided input can always form a valid BST.
In a Binary Search Tree, for every node:
All values in the left subtree are strictly less than the node’s value.
All values in the right subtree are strictly greater than the node’s value.
In preorder traversal, we visit the current node first, then recursively traverse the left subtree, followed by the right subtree.
Input: preorder = [6, 3, 2, 5, 9, 8, 11]
Output: [6, 3, 9, 2, 5, 8, 11]
Input: preorder = [4, 2, 7]
Output: [4, 2, 7]
Accepted:
Submission: