Skip to content

Instantly share code, notes, and snippets.

@adsteel
Created July 28, 2017 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adsteel/b3711cadc0d24c48249eaa27d90c5b39 to your computer and use it in GitHub Desktop.
Save adsteel/b3711cadc0d24c48249eaa27d90c5b39 to your computer and use it in GitHub Desktop.
Elixir Binary Search Tree
defmodule BSTNode do
@null "NULL"
defstruct [:value, :left, :right]
def new(value, left \\ BSTNode.empty, right \\ BSTNode.empty) do
%{value: value, left: left, right: right}
end
def empty do
new(@null, nil, nil)
end
def find(bstnode, value) do
cond do
bstnode.value == @null -> false
bstnode.value == value -> true
bstnode.value > value -> find(bstnode.left, value)
bstnode.value < value -> find(bstnode.right, value)
end
end
def add(bstnode, value), do: add(bstnode, value, bstnode)
def add(remaining_node, value, top_node, new_node_path \\ []) do
cond do
remaining_node.value == @null ->
put_in(top_node, new_node_path, new(value))
remaining_node.value == value -> top_node
remaining_node.value > value ->
add(remaining_node.left, value, top_node, new_node_path ++ [:left])
remaining_node.value < value ->
add(remaining_node.right, value, top_node, new_node_path ++ [:right])
end
end
end
defmodule Test do
def assert(msg, expected, actual) do
case actual == expected do
true -> IO.puts "#{msg} passed!"
false -> IO.puts "#{msg} failed. Expected #{inspect expected}, but got #{inspect actual}"
end
end
end
n = BSTNode.new(3)
|> BSTNode.add(1)
|> BSTNode.add(5)
|> BSTNode.add(4)
Test.assert("1", 5, n.right.value)
Test.assert("2", 4, n.right.left.value)
Test.assert("3", 1, n.left.value)
Test.assert("4", 3, n.value)
Test.assert("5", true, BSTNode.find(n, 1))
Test.assert("6", true, BSTNode.find(n, 3))
Test.assert("7", true, BSTNode.find(n, 5))
Test.assert("8", true, BSTNode.find(n, 4))
Test.assert("9", false, BSTNode.find(n, 7))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment