Last active
April 11, 2018 13:41
-
-
Save pskl/f247ef6c98e854654f4052c63fa5a497 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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