Skip to content

Instantly share code, notes, and snippets.

@sashaafm
Created February 20, 2016 16:38
Show Gist options
  • Save sashaafm/bb1c4e38a3fd779be54d to your computer and use it in GitHub Desktop.
Save sashaafm/bb1c4e38a3fd779be54d to your computer and use it in GitHub Desktop.
edpth-first search Elixir
@doc """
Does a Depth-First Search in the given 'tree'. The nodes' values are
returned in a list. The order of the search is passed into 'order' using
the atoms ':in_order', ':pre_order' or ':post_order'
"""
@spec depth_first_search(%{}, atom) :: list(any)
def depth_first_search(tree, order) when order == :pre_order or
order == :in_order or
order == :post_order do
dfs tree, order
end
defp dfs(:leaf, _), do: []
defp dfs(%{value: val, left: :leaf, right: :leaf}, _), do: [val]
defp dfs(tree_node, order) do
case order do
:pre_order ->
[tree_node.value] ++ dfs(tree_node.left, order) ++ dfs(tree_node.right, order)
:in_order ->
dfs(tree_node.left, order) ++ [tree_node.value] ++ dfs(tree_node.right, order)
:post_order ->
dfs(tree_node.left, order) ++ dfs(tree_node.right, order) ++ [tree_node.value]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment