Problem
Given an integern, 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.
Examples
Constraints
1 <= n <= 8
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 95 with 24 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 95 # by problem number
lcpy gen -s unique_binary_search_trees_ii # by problem name
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]]
Input: n = 1
Output: [[1]]
1 <= n <= 8from leetcode_py import TreeNode
class Solution:
# Time: O(4^n / sqrt(n) * n)
# Space: O(4^n / sqrt(n) * n)
def generate_trees(self, n: int) -> list[TreeNode[int] | None]:
def build(start: int, end: int) -> list[TreeNode[int] | None]:
if start > end:
return [None]
trees: list[TreeNode[int] | None] = []
for root_val in range(start, end + 1):
for left in build(start, root_val - 1):
for right in build(root_val + 1, end):
root = TreeNode[int](root_val)
root.left = left
root.right = right
trees.append(root)
return trees
return build(1, n)
| Time | Space |
|---|---|
| O(4^n / sqrt(n) * n) | O(4^n / sqrt(n) * n) |