Skip to content

Instantly share code, notes, and snippets.

@vedantk
Created December 5, 2011 02:54
Show Gist options
  • Save vedantk/1432100 to your computer and use it in GitHub Desktop.
Save vedantk/1432100 to your computer and use it in GitHub Desktop.
Binary search trees in Erlang
-module(bst).
-export([bst_create/0, bst_insert/2, bst_search/2]).
bst_create() -> [].
bst_insert(Bst, N) ->
case Bst of
[] -> [N, [], []];
[Root, Lhs, Rhs] ->
if
N == Root -> Bst;
N < Root -> [Root, bst_insert(Lhs, N), Rhs];
N > Root -> [Root, Lhs, bst_insert(Rhs, N)]
end
end.
bst_search(Bst, N) ->
case Bst of
[] -> false;
[Root, Lhs, Rhs] ->
if
N == Root -> true;
N < Root -> bst_search(Lhs, N);
N > Root -> bst_search(Rhs, N)
end
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment