Engineering platform~25 min2s · 256 MBtarget O(n^2) time, O(n) spaceclassic twin: lc-96dp · tree-recursion
A configuration service keeps n setting keys in a binary search tree. The keys are all different and sorted. The tree must keep the search order: a key in a left part is smaller than its parent, and a key in a right part is larger.
Many trees can hold the same keys. A chain, a balanced tree and a zigzag all do. Before a benchmark, the platform team asks how many different tree shapes exist for n keys, so they can size the test run.
Two trees are different when some key has a different left child or a different right child.
Write count_tree_shapes(n).
n keys 1, 2, ..., n, each key used once.1000003.Input: n = 4
Output: 14Count the shapes for 0, 1, 2, 3 and 4 keys, one size after the other. Choose the root, then multiply the count for the keys below it by the count for the keys above it.
| Keys | Root choices and their products | Shapes |
|---|---|---|
| 0 | the empty tree | 1 |
| 1 | 1 × 1 | 1 |
| 2 | 1 × 1 + 1 × 1 | 2 |
| 3 | 1 × 2 + 1 × 1 + 2 × 1 | 5 |
| 4 | 1 × 5 + 1 × 2 + 2 × 1 + 5 × 1 | 14 |
Input: n = 1
Output: 1One key makes one tree.
Input: n = 3
Output: 5The root can be 1, 2 or 3.
Root 1 has two shapes for the keys above it. Root 2 has one shape on each side. Root 3 has two shapes for the keys below it. That makes 2 + 1 + 2 = 5.
1 ≤ n ≤ 20001000003A solution that tries every root and recounts both sides from nothing makes about 3^n calls. For 20 keys that is already billions of calls.
The number of shapes for a given count of keys never changes. Work out each size once, from the smallest up. Then every size costs one pass over the root choices, and the whole job costs about n^2 / 2, or two million steps for n = 2000.