Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Fun with trees

tree.livemd

Fun with trees

Binary trees

Mix.install([{:kino, "~> 0.5.0"}])
defmodule Tree do
  defstruct [:left, :item, :right]

  def from_array([]), do: nil

  def from_array(list) do
    m = floor(length(list) / 2)
    [item | right] = Enum.drop(list, m)

    %Tree{
      left: from_array(Enum.take(list, m)),
      item: item,
      right: from_array(right)
    }
  end

  def depth(nil), do: 0
  def depth(%Tree{left: l, right: r}), do: 1 + max(depth(l), depth(r))
end

defimpl Inspect, for: Tree do
  import Inspect.Algebra

  def inspect(%Tree{left: l, item: i, right: r}, opts) do
    tree_to_doc = fn t -> if t == nil, do: ".", else: to_doc(t, opts) end
    concat(["<", tree_to_doc.(l), to_doc(i, opts), tree_to_doc.(r), ">"])
  end
end
%Tree{item: 1}
size_input = Kino.Input.text("size")
{size, _} = size_input |> Kino.Input.read() |> String.trim() |> Integer.parse()
size
items = Enum.to_list(1..size)
tree = Tree.from_array(items)
Tree.depth(tree)