Given an integer n, count the different binary search trees that hold the values 1 to n, each exactly once.
In a binary search tree, every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger. Two trees count as different when their shapes differ. With the values fixed to 1 to n, the shape decides where every value goes, so counting trees is the same as counting shapes.
Example 1
Input: n = 2
Output: 2
Either value can be the root. The other one then has only one place to go: to the right of 1, or to the left of 2.
Example 2
Input: n = 4
Output: 14
This is one of the fourteen trees: 3 at the root, 1 and 2 on its left, and 4 on its right.
Example 3
Input: n = 5
Output: 42
Constraints
1 <= n <= 19Pick the value that sits at the root. Every smaller value must go in its left subtree and every larger one in its right, and the two sides can be shaped independently of each other.
2
2