You're given an array of unique integers that represents a potential preorder traversal sequence of a Binary Search Tree (BST). Your task is to determine if this sequence could actually be generated by traversing a valid BST in preorder.
In a preorder traversal, we visit nodes in this order: root โ left subtree โ right subtree. For a valid BST, all values in the left subtree must be smaller than the root, and all values in the right subtree must be larger than the root.
Goal: Return true if the given array represents a valid BST preorder traversal, false otherwise.
Example: For [5,2,1,3,6], this could represent a BST where 5 is root, left subtree contains [2,1,3], and right subtree contains [6]. This follows BST properties, so return true.
Input & Output
Constraints
- 1 โค preorder.length โค 104
- 1 โค preorder[i] โค 104
- All integers in preorder are unique