KatInterview

96. Unique Binary Search Trees

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the total number of structurally unique Binary Search Trees (BSTs) that can be constructed using n nodes with unique values from 1 to n. The key is that the structure matters, not just the arrangement of values. For example, for n=3, the nodes are {1, 2, 3}. A tree with root 2, left child 1, and right child 3 is one valid BST. We need to find all such unique structures.

Solution

Unique Binary Search Trees in Python

class Solution:
    def numTrees(self, n: int) -> int:
        # Let G(n) be the number of unique BSTs for n nodes.
        # This problem is equivalent to finding the n-th Catalan number.
        # The recurrence relation is:
        # G(n) = sum_{i=1 to n} G(i-1) * G(n-i)
        # G(0) = 1 (empty tree)
        # G(1) = 1 (single node tree)
        
        # We can use dynamic programming to solve this.
        # dp[i] will store the number of unique BSTs for i nodes.
        dp = [0] * (n + 1)
        
        # Base case: There's one unique BST for 0 nodes (the empty tree).
        dp[0] = 1
        
        # Calculate dp[i] for i from 1 to n.
        for i in range(1, n + 1):
            # To calculate dp[i], we iterate through all possible roots j (from 1 to i).
            for j in range(1, i + 1):
                # If j is the root, the left subtree has j-1 nodes,
                # and the right subtree has i-j nodes.
                # The number of structures is the product of the possibilities
                # for the left and right subtrees.
                dp[i] += dp[j - 1] * dp[i - j]
                
        return dp[n]

Unique Binary Search Trees in Java

class Solution {
    public int numTrees(int n) {
        // Let G(n) be the number of unique BSTs for n nodes.
        // The number of unique BSTs is the sum of possibilities with each number as the root.
        // If we choose i as the root (1 <= i <= n), then:
        // - The left subtree will be formed by numbers {1, ..., i-1}, which has i-1 nodes.
        //   The number of ways is G(i-1).
        // - The right subtree will be formed by numbers {i+1, ..., n}, which has n-i nodes.
        //   The number of ways is G(n-i).
        // Total for root i is G(i-1) * G(n-i).
        // So, G(n) = sum from i=1 to n of (G(i-1) * G(n-i)).
        // This is the formula for Catalan numbers.

        // We use dynamic programming to solve this.
        // dp[i] will store G(i).
        int[] dp = new int[n + 1];

        // Base case: G(0) = 1. There is one way to form a BST with 0 nodes (the empty tree).
        dp[0] = 1;

        // Iterate from 1 to n to compute G(i) for each i.
        for (int i = 1; i <= n; i++) {
            // To calculate G(i), we iterate through all possible roots j (from 1 to i).
            for (int j = 1; j <= i; j++) {
                // Root is j.
                // Left subtree has j-1 nodes.
                // Right subtree has i-j nodes.
                dp[i] += dp[j - 1] * dp[i - j];
            }
        }

        // The result for n nodes is in dp[n].
        return dp[n];
    }
}

Unique Binary Search Trees in C++

class Solution {
public:
    int numTrees(int n) {
        // G(n): the number of unique BST for a sequence of length n.
        // G(n) = F(1, n) + F(2, n) + ... + F(n, n), where F(i, n) is the number of BSTs with root i.
        // F(i, n) = G(i-1) * G(n-i).
        // So, G(n) = sum_{i=1 to n} G(i-1) * G(n-i). This is the Catalan number.
        
        // dp[i] will store G(i).
        std::vector<int> dp(n + 1, 0);
        
        // Base case: G(0) = 1 (an empty tree is a valid BST).
        dp[0] = 1;
        
        // Calculate dp[i] for i from 1 to n.
        for (int i = 1; i <= n; ++i) {
            // To calculate dp[i], we sum up the possibilities for each root j.
            for (int j = 1; j <= i; ++j) {
                // j is the root.
                // Left subtree has j-1 nodes.
                // Right subtree has i-j nodes.
                // Number of trees = (trees in left) * (trees in right).
                dp[i] += dp[j - 1] * dp[i - j];
            }
        }
        
        return dp[n];
    }
};

Unique Binary Search Trees in TypeScript

function numTrees(n: number): number {
    // Let G(n) be the number of unique BSTs for n nodes.
    // This problem is a classic dynamic programming problem, and the solution
    // is the n-th Catalan number.
    // The recurrence relation is G(n) = Σ_{i=1 to n} G(i-1) * G(n-i).
    // This is derived by considering each number `i` from 1 to `n` as the root.
    // If `i` is the root, there are `i-1` nodes in the left subtree and `n-i` nodes
    // in the right subtree.

    // dp[i] will store G(i).
    const dp = new Array<number>(n + 1).fill(0);

    // Base case: G(0) = 1. An empty tree is considered one unique structure.
    dp[0] = 1;

    // Build up the dp table from i = 1 to n.
    for (let i = 1; i <= n; i++) {
        // To compute dp[i], we sum over all possible root choices `j` from 1 to `i`.
        for (let j = 1; j <= i; j++) {
            // When `j` is the root:
            // Left subtree has `j-1` nodes.
            // Right subtree has `i-j` nodes.
            // The total number of trees for this root choice is the product.
            dp[i] += dp[j - 1] * dp[i - j];
        }
    }

    return dp[n];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.