For red ebony, you do not need to track the number of nodes on the left, because if it is correctly offset (should be), then the number of left nodes will always consist of a series of Mersenne (1, 3, 7, 15, 31 ...) or 2^depth -1 .
With that in mind, we can write the logic to recursively get the node. In the accepted answer, its button is indicated above . This is the correct implementation in the elixir. For package
def nth(%Rbtree{node: r}, n), do: do_nth(r, n) defp do_nth({_,h,k,v,l,r}, n) do l_count = left_count(h) cond do l_count > n -> case l do nil -> {k,v} _ -> do_nth(l, n) end l_count == n -> {k,v} true -> case r do nil -> {k,v} _ -> do_nth(r, n - l_count - 1) end end end defp left_count(1), do: 0 defp left_count(0), do: 0 defp left_count(h), do: :math.pow(2,h-1)-1 |> round
source share