Created
February 20, 2016 16:47
-
-
Save sashaafm/aeb3ffd586a8eb446261 to your computer and use it in GitHub Desktop.
breadth-first search Elixir
This file contains 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
@doc """ | |
Performs a Breadth-First Search in the given 'tree'. The nodes' values are | |
returned as a list. | |
""" | |
@spec breadth_first_search(%{}) :: list(any) | |
def breadth_first_search(tree) do | |
bfs(tree) | |
end | |
defp bfs(%{value: val, left: :leaf, right: :leaf}) do | |
[val] | |
end | |
defp bfs(%{value: val, left: :leaf, right: right}) do | |
[val] ++ bfs(right) | |
end | |
defp bfs(%{value: val, left: left, right: :leaf}) do | |
[val] ++ bfs(left) | |
end | |
defp bfs(%{value: val, left: left, right: right}) do | |
[val] ++ bfs(left) ++ bfs(right) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment