Unique Binary Search Trees
Description
Given n, how many structurally unique BSTs (binary search trees) that store values 1 ... n?
Example:
Solution
Let dp[i]
be the number of BSTs that stores 1..i
. dp[0] = 1
if we consider the tree with root = null
is also a BST.
To store 1..n
in a BST, we can select i=1,...n
as the root node. Then there are i-1
nodes on the left sub-tree and n-i
nodes on the right sub-tree. Thus, the number of BSTs that stores 1..n
and has i
as the root node is dp[i-1] * dp[n-i]
.
So, the total number of BSTs that stores 1..n
is:
Last updated