LeetcodeAug 27, 2025

Unique Binary Search Trees

Hazrat Ali

Leetcode

Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.

 

Example 1:

Input: n = 3
Output: 5

Example 2:

Input: n = 1
Output: 1


Solution
/**
 *
 * @param {number} n
 * @return {number}
 */
const numTrees = n => {
 
  if (n <= 0) {
    return 0;
  }

  const dp = [1];

  for (let i = 1; i <= n; i++) {
    let count = 0;
    for (let j = 1; j <= i; j++) {
      count += dp[j - 1] * dp[i - j];
    }
    dp[i] = count;
  }

  return dp[n];
};
 

Comments