Skip to content

Instantly share code, notes, and snippets.

@pskl
Last active April 11, 2018 13:41
Show Gist options
  • Save pskl/f247ef6c98e854654f4052c63fa5a497 to your computer and use it in GitHub Desktop.
Save pskl/f247ef6c98e854654f4052c63fa5a497 to your computer and use it in GitHub Desktop.
# Given a number of keys how many binary search trees can be formed?
def num_trees(n)
return 1 if n == 0 || n == 1
(1..n).map do |j|
num_trees(j - 1) * num_trees(n - j) # left * right (summed)
end.reduce(:+)
end
p num_trees 0 # should be 1
p num_trees 1 # should be 1
p num_trees 2 # should be 2
p num_trees 3 # should be 5
p num_trees 5 # should be 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment