#96

Unique Binary Search Trees

Medium
MathDynamic ProgrammingTreeBinary Search TreeBinary TreeDynamic ProgrammingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal solution uses dynamic programming to store the number of unique BSTs for each number of nodes, avoiding redundant calculations. This is based on the Catalan number formula, which counts the unique BSTs efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create an array dp of size n+1 initialized to 0, with dp[0] = 1 (base case).
  2. 2Step 2: For each i from 1 to n, calculate dp[i] by considering each j from 1 to i as the root.
  3. 3Step 3: For each root j, the number of unique trees is dp[j-1] (left) * dp[i-j] (right). Sum these products to get dp[i].
  4. 4Step 4: Return dp[n] as the result.
solution.py7 lines
1def numTrees(n):
2    dp = [0] * (n + 1)
3    dp[0] = 1
4    for i in range(1, n + 1):
5        for j in range(1, i + 1):
6            dp[i] += dp[j - 1] * dp[i - j]
7    return dp[n]

Complexity note: The time complexity is O(n²) due to the nested loops, but we save results in dp to avoid recalculating, leading to a linear space complexity.

  • 1The number of unique BSTs can be derived from the structure of smaller trees.
  • 2Dynamic programming helps to avoid redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.