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 ≤ n ≤ 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:
$$ G(n)=\sum_{i=1}^n f(i) $$
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
f(i) = G(i − 1) × G(n − i)
Fusing above two equations, the Catalan Number Equation is deduced:
$$ G(n)=\sum_{i=0}^n G(i)\times G(n-1-i) $$