LeetCode-in-All

96. Unique Binary Search Trees

Medium

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:

Solution

-spec num_trees(N :: integer()) -> integer().
num_trees(N) ->
    Result = calculate_num_trees(N, 0, 1),
    Result div (N + 1).

-spec calculate_num_trees(N :: integer(), I :: integer(), Acc :: integer()) -> integer().
calculate_num_trees(N, I, Acc) when I >= N ->
    Acc;
calculate_num_trees(N, I, Acc) ->
    calculate_num_trees(
        N,
        I + 1,
        (Acc * (2 * N - I)) div (I + 1)
    ).