Unique Binary Search Trees
Given a 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; |
Constraints:
$1 \le n \le 19$
Solution
1 | class UniqueBinarySearchTrees { |
Explanation:
Assume that the number of BSTs of $n$ nodes is $G(n)$, and $f(i)$ denotes the number of BSTs whose root value is $i$, thus:
And when $i$ is the root node, the number of nodes of its left subtree is $i-1$, and the number of nodes of its right subtree is $n-i$, thus
Fusing above two equations, the Catalan Number Equation is deduced: