Skip to content

Instantly share code, notes, and snippets.

@wpcarro
Created May 29, 2017 18:56
Show Gist options
  • Save wpcarro/adb2c06df752f003b964c93aa68cca06 to your computer and use it in GitHub Desktop.
Save wpcarro/adb2c06df752f003b964c93aa68cca06 to your computer and use it in GitHub Desktop.
Simple implementation of a breadth-first tree traversal written in Elixir
defmodule Tree do
@moduledoc """
Simple implementation of a breadth-first tree traversal.
Author: William Carroll
"""
@type value :: any
@type tree :: {value [tree]}
@spec bf_print_tree(tree) :: :ok
def bf_print_tree(tree) do
queue =
:queue.in(tree, :queue.new())
do_bf_print_tree(queue)
end
@spec do_bf_print_tree(:queue.queue(tree)) :: :ok
defp do_bf_print_tree(queue) do
case :queue.out(queue) do
{{:value, {value, children}}, queue} ->
IO.inspect(value)
queue =
case children do
nil ->
queue
children when is_list(children) ->
children
|> Enum.reduce(queue, & :queue.in(&1, &2))
end
do_bf_print_tree(queue)
{:empty, _} ->
nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment