Q: Via Quora
Given the set of keys {6, 7, 1, 4, 2}, how many unique binary search trees of height 2 are possible? Draw the trees. Assume that the height of the root-node is zero.
A:
There are 6 unique Binary Search Trees (BST) of height 2 that can be constructed from the key set
$\{ 6, 7, 1, 4, 2 \}$ when all keys are used. Furthermore, there are 36 total BSTs of height 2 that can be constructed from said key set.
Let’s understand how and why.
-
An approach to this problem is to first calculate every possible permutation of the keys which should give you
$5! = 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1 = 120$ permutations. -
Then attempt to construct a BST for every single permutation. However, once the height of the current BST exceeds a specified height limit, we halt and skip the current iteration.
-
The steps hitherto generate all BSTs of the specified height based on the permutated sequences
of the original keys. However, different sequences can still produce the same BST. To address this, we ensure to perform level-oriented traversal i.e. Breadth-First Search (BFS), for every BST and then filter and verify if the traversal results had been obtained earlier or not. -
The resulting collection of BSTs will be unique, consisting of all elements in the original set of keys, with the exact height specified.
-
We now introduce a tree printing heuristic that illustrates each BST.
Implementation (see unique_bst.py
)
This is a factorial time algorithm (proportional to the size of the original keys), implementing a brute-force technique in constructing unique BSTs based off a permutation of keys. Furthermore, this particular pattern is known as backtracking - halting a specific iteration within an algorithm when an unwanted condition is encountered while exploring every other possible conditional case.
Fun Fact: The resulting BSTs from this particular key set are all AVL-compliant!
All BSTs of height 2 = 36
6
/ \
/ \
/ \
2 7
/ \
1 4
4
/ \
/ \
/ \
2 7
/ /
1 6
4
/ \
/ \
/ \
1 6
\ \
2 7
4
/ \
/ \
/ \
2 6
/ \
1 7
2
/ \
/ \
/ \
1 6
/ \
4 7
4
/ \
/ \
/ \
1 7
\ /
2 6
Number of unique BSTs of height 2 from set of keys <6, 7, 1, 4, 2> = 6
Brute-force and factorial time algorithms should be avoided as much as possible in favor for an algorithmically correct and efficient alternative when feasible. For a potentially efficient solution exploiting combinatorial evaluation, consider this StackOverflow post on a similar question.