Created
February 20, 2016 16:38
-
-
Save sashaafm/bb1c4e38a3fd779be54d to your computer and use it in GitHub Desktop.
edpth-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 """ | |
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