Skip to content

Instantly share code, notes, and snippets.

@coproduto
Last active December 30, 2024 00:16
Show Gist options
  • Save coproduto/6d76bfba610ad026a82144e9a44f1a24 to your computer and use it in GitHub Desktop.
Save coproduto/6d76bfba610ad026a82144e9a44f1a24 to your computer and use it in GitHub Desktop.
defmodule LevelOrderTraversal do
# Nós da árvore representados como {valor, {filho_direita, filho_esquerda}}
@type tree :: {term, {tree | nil, tree | nil}}
# Função que converte a árvore em seus níveis
@spec traverse(tree) :: [[term]]
def traverse(nil), do: [[]]
def traverse({x, {l, r}}) do
[[x] | Enum.zip_with(traverse(l), traverse(r), &Enum.concat/2)]
end
def traverse(x), do: [[x]]
@spec print(tree) :: :ok
def print(tree) do
tree
|> traverse()
|> Enum.map(fn level ->
level
|> Enum.join(" ")
|> IO.puts()
end)
:ok
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment