Created
December 5, 2011 02:54
-
-
Save vedantk/1432100 to your computer and use it in GitHub Desktop.
Binary search trees in Erlang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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