LeetCode 96: Unique Binary Search Trees Solution

Master LeetCode problem 96 (Unique Binary Search Trees), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. The problem can be approached by defining a function numTrees(n) that represents the number of unique BSTs that can be formed with n nodes. We can use the following recurrence relation:

numTrees(n) = numTrees(0)*numTrees(n-1) + numTrees(1)*numTrees(n-2) + ... + numTrees(k)*numTrees(n-k-1) + ... + numTrees(n-1)*numTrees(0)

The base case is numTrees(0) = 1 and numTrees(1) = 1.

We can maintain an array dp where dp[i] will store the number of unique BSTs that can be formed with i nodes. We then iterate over all possible numbers of nodes from 1 to n and calculate the number of unique BSTs using the above recurrence relation.

Time Complexity

The time complexity of this approach is O(n^2) as we iterate over all numbers from 1 to n and calculate the number of unique BSTs.

Space Complexity

The space complexity is O(n) to store the array dp.

Solution Code

class Solution {
    public int numTrees(int n) {
        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = 1;
        
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                dp[i] += dp[j - 1] * dp[i - j];
            }
        }
        
        return dp[n];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 96 (Unique Binary Search Trees)?

This page provides optimized solutions for LeetCode problem 96 (Unique Binary Search Trees) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 96 (Unique Binary Search Trees)?

The time complexity for LeetCode 96 (Unique Binary Search Trees) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 96 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 96 in Java, C++, or Python.

Back to LeetCode Solutions