Skip to the code
cf.
+25 XP

#493 Count Menu Tree Shapes

medium

A command menu stores n commands with ids 1 to n in a binary search tree: for every node, smaller ids are in its left subtree and larger ids are in its right subtree.

Different insertion orders can give trees of different shapes. Write countTreeShapes(n) that returns how many structurally different binary search trees hold exactly the ids 1 to n. For n = 0 the empty tree counts as one shape.

Example 1

Input: n = 3
Output: 5

Root 1 gives 2 shapes, root 2 gives 1, and root 3 gives 2.

Example 2

Input: n = 1
Output: 1

A single node.

Constraints

  • 0 <= n <= 19
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).