Skip to content

Instantly share code, notes, and snippets.

@sashaafm
Created February 20, 2016 16:47
Show Gist options
  • Save sashaafm/aeb3ffd586a8eb446261 to your computer and use it in GitHub Desktop.
Save sashaafm/aeb3ffd586a8eb446261 to your computer and use it in GitHub Desktop.
breadth-first search Elixir
@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