Problem: Given an array of integers, determine if it can be the postorder traversal sequence of a BST. Ex: [5, 7, 6, 9, 11, 10, 8]
returns true, but [7, 4, 6, 5]
returns false.
I'm wondering if we can do this in linear time. Here are solutions for N^2
and NlgN
I came up with.
N^2 solution
: Scan through the array and check the root's left and right subtree values are all smaller and larger than the root's value respectively. Repeat for each subtree.
NlgN solution
: Build a BST going from right to left of the input array. Keep track of some max number we can encounter at any point. This max number updates to the parent node every time we insert a left child. If we ever try to insert a node greater than the tracked max number, we can return false.