Unique Binary Search Trees Problem


Description

LeetCode Problem 96.

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:

1
2
Input: n = 3
Output: 5

Example 2:

1
2
Input: n = 1
Output: 1

Constraints:

  • 1 <= n <= 19


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
    int numTrees(int n) {
        if(n <= 1) return 1;
        int ans = 0;
        for(int i = 1; i <= n; i++) 
            ans += numTrees(i-1) * numTrees(n-i);
        return ans;
    }
};




Related Posts

Convert Sorted Array to Binary Search Tree Problem

LeetCode 108. Given an integer array nums where the elements...

Validate Binary Search Tree Problem

LeetCode 98. Given the root of a binary tree, determine...

Same Tree Problem

LeetCode 100. Given the roots of two binary trees p...

Recover Binary Search Tree Problem

LeetCode 99. You are given the root of a binary...

Unique Binary Search Trees Problem

LeetCode 96. Given an integer n, return the number of...

Unique Binary Search Trees II Problem

LeetCode 95. Given an integer n, return all the structurally...