BST Sequences
Last updated
Last updated
4.9 BST Sequences: A binary search tree was created by traversing through an array from left to right and inserting each element. Given a binary search tree with distinct elements, print all possible arrays that could have led to this tree.
Ex.
Output: {2, 1, 3}, {2, 3, 1}
Brain storm:
I first noticed that a pre order traversal nicely prints out a possible combination of the array. I can use this transversal once, and use the output array as the basis of the remainder of my combinations depending on a few properties.
I will have a level order traversal, which will check to see if has another sibling (same parent), by using the property of B-trees that children with siblings are expected to grow by 2^n in pairs of two per level. In a binary configuration, this will determine whether the number is flippable in the combination.
num unique flips = log_2(num flippables)
Each unique flip can be expressed as a combination on the number of states
num combination states = 2^(unique flip), an even number
In my pre-order tranversal array, each unique flip occurs with the next proceeding flip, and this will produce another combination based on the pre order combination.
Then, using each uniquely flipped array, we can write as a combination of the others, discluding itself and the preorder combination.
BigO:
Preorder traversal O(N)
Parent check O(2N)
More efficient and complete implementation