Ctrl K

Counting Search Tree Shapes

Medium
A binary search tree is built from the numbers 1, 2, …, n, each used exactly once: for every node, all values in its left subtree are smaller and all values in its right subtree are larger than its own. Return how many different search trees can be built this way. Two trees differ if their shape or the value at some position differs.
Example 1
n=2 → 2

The root is either 1 (with 2 as its right child) or 2 (with 1 as its left child). Two shapes.

Example 2
n=4 → 14

Roots 1, 2, 3 and 4 give 5 + 2 + 2 + 5 = 14 trees, since the subtrees left and right of the root are built independently.

Example 3
n=1 → 1
Constraints
  • 1 ≤ n ≤ 19
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsOther Orders for the Same Search Tree HardBiggest Search Subtree MediumHeaviest Search Subtree HardPruning Duel on a Growing Tree HardIs It a Search Tree? Medium
loading Python…
Input
n=2
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 17 tests on the server, hidden ones included.