DYNP-P1

Shapes of a search tree

Practice 1 of 9Dynamic programming9 tests

The problem

A binary search tree (TREE-3) can hold the same keys in many shapes. Return how many different binary search trees hold the keys 1, 2, …, n. Two trees are different if their shapes are different.

shapes(3)    # 5
shapes(0)    # 1: the empty tree
shapes(4)    # 14

A formula for this count exists, so math.comb, math.factorial and math.perm are switched off. Work it out from smaller counts.

Limits

  • n is from 0 to 200. The answers have up to 117 digits; Python’s whole numbers hold them exactly.
  • Memoised recursion is fine here: it goes at most 200 calls deep.

Builds on DYNP-1 Overlapping subproblems.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2No keysNot run
3One keyNot run
4Two keysNot run
5Four keysNot run
6Ten keysNot run
725 keysNot run
8120 keysNot run
9200 keysNot run