447. Verify Preorder Sequence in Binary Search Tree
Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.
Example 1:
Input: preorder = [5,2,1,3,6]
Explanation: We check whether this sequence represents a valid preorder traversal of a BST.
- Start with root = 5.
- 2 is smaller than 5, so it becomes the left child.
- 1 is smaller than 2, so it becomes the left child of 2.
- 3 is greater than 2 but smaller than 5, so it becomes the right child of 2.
- 6 is greater than 5, so it becomes the right child of 5.
Since all elements follow the properties of a BST Preorder Traversal, the answer is true.
Output : true
Example 2:
Input: preorder = [5,2,6,1,3]
Explanation:We check whether this sequence represents a valid preorder traversal of a BST.
Start with root = 5.
- 2 is smaller than 5, so it becomes the left child.
- 6 is greater than 5, so it becomes the right child.
- 1 is smaller than 2, so it becomes the left child of 2.
- 3 is greater than 2, but we have already placed 6 as the right child of 5, meaning all further values should be greater than 5. However, 3 is smaller than 5, which violates BST properties.
Since this does not form a valid BST preorder traversal, the answer is false.
Output: false
Now Your Turn!
Pick the correct output for the given inputInput: preorder = [1,2,3,4,5]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= preorder.length <= 104
- 1 <= preorder[i] <= 104
- All the elements of preorder are unique.