Unique Binary Search Trees

Given an integer n, return the number of structurally unique binary search trees that store exactly the values 1 to n, each value used once.

30:00

Unique Binary Search Trees
medium
Free written solution
Topics
Companies

Given an integer n, return the number of structurally unique binary search trees that store exactly the values 1 to n, each value used once.

Example 1:
Input: {"n":3}
Output: 5
Constraints:
  • 1≤n≤191 \leq n \leq 19

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":3}

G[k] will count BST shapes on k keys. Only the count of keys matters, not their values. G[0] = 1: the empty tree is one shape.

Count shapes, not values

left subtree

root

right subtree

A BST on any k sorted keys has the same number of shapes as one on keys 1..k.

G[k] = shapes on k keys

1

0

?

1

?

2

?

3

Variables
VariableValue
n3
G[0]1
DepthFunction Call
Stack empty
0/10