Unique Binary Search Trees
Real-world version: Shapes of the Docket RegistryThe statement here is our own: the same inputs, outputs and technique.
A claims office files dockets numbered 1 through n into a search tree. Each docket occupies exactly one node, and each node has at most two nodes hanging off it, one called its lower child and one called its upper child.
The filing rule is that for every node, every docket sitting anywhere beneath its lower child carries a smaller number, and every docket sitting anywhere beneath its upper child carries a larger number.
Two registries are considered different when some docket has a different lower child or a different upper child in one than in the other. Return how many different registries can be built from dockets 1 through n.
Examples
Example 1
- Input
- n = 6
- Output
- 132
Six dockets can be filed in 132 different registries.
Example 2
- Input
- n = 9
- Output
- 4862
Nine dockets can be filed in 4862 different registries.
Example 3
- Input
- n = 4
- Output
- 14
With four dockets there are 14 registries. Putting docket 2 at the top, for instance, forces docket 1 into its lower branch and leaves dockets 3 and 4 for the upper branch, which they can fill in two ways.
Constraints
- 1 <= n <= 25
- The largest allowed n gives an answer of 4861946401452, so every answer stays below 5 * 10^12.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def num_trees(n: int) -> int:public long numTrees(int n)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Unique Binary Search Trees IIReal-world version: Every Search Tree Over the First n LabelsMedium
- Maximum Sum BST in Binary TreeReal-world version: The Heaviest Sorted Section of a RigHard
- Convert Sorted Array to Binary Search TreeReal-world version: Balanced Marker IndexEasy
- Two Sum IV - Input is a BSTReal-world version: Two Calibration Cards to a TargetEasy