Given an integer n, the task is to generate all possible Binary Search Trees (BSTs) that can be constructed using keys from 1 to n and print their preorder traversal.
How many structurally unique BSTs can be formed with keys from 1 to n?
The key observation is that for any i-th number chosen as the root, all numbers from 1 to i-1 must be in the left subtree (since they are smaller than the root), and all numbers from i+1 to n must be in the right subtree (since they are larger than the root).
If the numbers from 1 to i-1 can form x different trees and the numbers from i+1 to n can form y different trees, then for the i-th number as root, we can have x * y total unique BSTs.
Since we can choose any number from 1 to n as the root, we iterate over each possible root (from 1 to n) and calculate the total number of unique BSTs by summing up the product of the number of left and right subtrees for each root.
Upon observation, the number of structurally unique BSTs for n keys is equivalent to the n-th Catalan number, which can be computed using known formulas or dynamic programming.
Approach:
The idea is to construct all possible BSTs by considering each number from 1 to n as the root and recursively constructing the left and right subtrees. For each root i, all numbers from 1 to i-1 will form the left subtree, and numbers from i+1 to n will form the right subtree. We recursively generate all possible BSTs for the left and right subtrees and then combine each left subtree with each right subtree for the current root.
Follow the steps below to solve the problem:
Initialize a array of BSTs as empty.
For every number i from 1 to n, do the following:
Create a new node with key i, let this node be 'node'.
Recursively construct a list of all possible left subtrees from numbers 1 to i-1.
Recursively construct a list of all possible right subtrees from numbers i+1 to n.
Iterate over all possible left subtrees:
For each current left subtree, iterate over all possible right subtrees.
Attach the current left and right subtrees to 'node'.
Add the node (with attached subtrees) to the list of BSTs.
Below is the implementation of the above approach:
Output
1 2 3
1 3 2
2 1 3
3 1 2
3 2 1
Time Complexity: O(Cn * n), where Cn is the Catalan number Auxiliary Space: O(Cn * n), for storing all possible trees and the space used by the recursion stack.