Skip to content

Instantly share code, notes, and snippets.

@sashaafm
Created February 20, 2016 15:55
Show Gist options
  • Save sashaafm/4a0519c0aca08734d034 to your computer and use it in GitHub Desktop.
Save sashaafm/4a0519c0aca08734d034 to your computer and use it in GitHub Desktop.
insert bst
def new(value) do
%{value: value, left: :leaf, right: :leaf}
end
@doc """
Creates and inserts a node with its value as 'node_value' into the tree.
"""
@spec insert(%{} | :leaf, any) :: %{}
def insert(:leaf, node_value), do: new node_value
def insert(%{value: value, left: left, right: right}, node_value) do
if node_value < value do
%{value: value, left: insert(left, node_value), right: right}
else
%{value: value, left: left, right: insert(right, node_value)}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment