304 North Cardinal St.
Dorchester Center, MA 02124

# Unique Binary Search Trees LeetCode Solution

## Problem – Unique Binary Search Trees LeetCode Solution

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
``````

Constraints:

• `1 <= n <= 19`

## Unique Binary Search Trees LeetCode Solution in Java

``````public int numTrees(int n) {
int [] dp = new int[n+1];
dp= 1;
dp = 1;
for(int level = 2; level <=n; level++)
for(int root = 1; root<=level; root++)
dp[level] += dp[level-root]*dp[root-1];
return dp[n];
}
``````

## Unique Binary Search Trees LeetCode Solution in C++

``````class Solution {
public:
int dp{};
int numTrees(int n) {
if(n <= 1) return 1;
if(dp[n]) return dp[n];
for(int i = 1; i <= n; i++)
dp[n] += numTrees(i-1) * numTrees(n-i);
return dp[n];
}
};
``````

## Unique Binary Search Trees LeetCode Solution in Python

``````class Solution:
@cache
def numTrees(self, n: int) -> int:
if n <= 1: return 1
return sum(self.numTrees(i-1) * self.numTrees(n-i) for i in range(1, n+1))``````
##### Unique Binary Search Trees LeetCode Solution Review:

In our experience, we suggest you solve this Unique Binary Search Trees LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Unique Binary Search Trees LeetCode Solution

Find on Leetcode

##### Conclusion:

I hope this Unique Binary Search Trees LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions