/95. Unique Binary Search Trees II

95. Unique Binary Search Trees II

Medium
Dynamic Programming62.1% acceptance

Given an integer node_count, generate all structurally unique binary search trees (BSTs) that have exactly node_count nodes with unique values from 1 to node_count. Return the list of all possible BSTs, where each BST is represented as a nested TreeNode structure. The order of the returned BSTs does not matter.

Example 1

Input: 2

Output: [TreeNode(1, None, TreeNode(2)), TreeNode(2, TreeNode(1), None)]

Explanation: There are two unique BSTs for node_count = 2: one with 1 as root and 2 as right child, and one with 2 as root and 1 as left child.

Example 2

Input: 4

Output: A list of 14 unique BSTs with values from 1 to 4

Explanation: There are 14 unique BSTs for node_count = 4, each using values 1 to 4 exactly once.

Constraints

  • 1 <= node_count <= 8
  • Each BST must use all values from 1 to node_count exactly once
  • Return all structurally unique BSTs
Python (current runtime)

Case 1

Input: 3

Expected: A list of 5 unique BSTs with values from 1 to 3

Case 2

Input: 5

Expected: A list of 42 unique BSTs with values from 1 to 5