Given an integer n
, return all the structurally unique BST’s (binary search trees), which has exactly n
nodes of unique values from 1 to n
. Return the answer in any order.
Input: n = 3
Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
[None]
as there’s no valid tree in this range.from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def generateTrees(n: int) -> List[Optional[TreeNode]]:
if n == 0:
return []
def generate(start, end):
if start > end:
return [None]
all_trees = []
for i in range(start, end + 1):
left_trees = generate(start, i - 1)
right_trees = generate(i + 1, end)
for l in left_trees:
for r in right_trees:
current_tree = TreeNode(i)
current_tree.left = l
current_tree.right = r
all_trees.append(current_tree)
return all_trees
return generate(1, n)
# Example usage:
# Output will be trees in the form of TreeNode objects.
# To visualize, you might need additional helper functions.
for tree in generateTrees(3):
print(tree)
The time complexity is a bit complex to determine due to the nature of the problem, but it’s generally considered to be catalan number related which is O((2^n) * n)
to generate all unique BSTs. Here n
is the given integer determining the number of unique nodes in the BST.
This problem fits within the dynamic programming and recursion domain with memoization to optimize the performance over the brute-force approach.
Feel free to test the function with the provided example or other values of n
to ensure it works as expected.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?