Build binary tree from level order array

(…) if a node has an index i , its children are found at indices 2i+1 (for the left child) and 2i+2 (for the right) (…)

Source: Arrays at Binary tree | Wikipedia

With above writing code is really simple:

defmodule TreeNode do
  defstruct ~w[data left right]a
end

defmodule Example do
  def sample(input, index \\ 0) do
    data = Enum.at(input, index)

    unless data in [nil, -1] do
      %TreeNode{
        data: data,
        left: sample(input, index * 2 + 1),
        right: sample(input, index * 2 + 2)
      }
    end
  end
end

iex> Example.sample([1, 2, 3, -1, -1, -1, -1])
%TreeNode{
  data: 1,
  left: %TreeNode{data: 2, left: nil, right: nil},
  right: %TreeNode{data: 3, left: nil, right: nil}
}