255 Verify Preorder Sequence in Binary Search Tree
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
You may assume each number in the sequence is unique.
The Idea: In a preorder traversal of a BST, we notice the following things. A preorder traversal follows LVR (value, left, right). We observe the following: One, all the parent elements are larger than it's left children, which exception to the root. Secondly, when the number is greater than the element, then we ascending right once, before we can move left again.
Complexity: O(n) time where n is the number of elements and O(h) space where h is the height of the tree.
Last updated