Problem Description
Given an integer n, generate all structurally unique binary search trees (BSTs) that store values 1 to n. Each BST must have exactly n nodes where each node value is unique from 1 to n.
Key Insights
- Utilize a recursive (divide and conquer) approach where each number in the range can be chosen as the root.
- For a chosen root, all numbers less than the root become part of the left subtree, and all numbers greater become part of the right subtree.
- Recursively generate all valid left and right subtrees then combine them to form unique BSTs.
- Base case: When the starting index exceeds the ending index, return a list containing None (or null in other languages) to represent an empty tree.
- The problem essentially generates trees corresponding to Catalan numbers.
Space and Time Complexity
Time Complexity: O(n * Catalan(n))
Space Complexity: O(n * Catalan(n)) (space used to store all generated trees and recursion stack)
Solution
We use a recursive function that accepts a range (start, end) and returns all possible BSTs constructed from numbers within that range. For every possible root value within the range, we recursively generate all possible left subtrees (from start to value-1) and right subtrees (from value+1 to end). We then iterate over every combination of left and right subtree and create a new tree node with the selected root value. This tree is appended to our list of unique BSTs. Key details include handling the base case where the start index exceeds the end index (which represents an empty subtree) and combining results appropriately.