-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbst.erl
40 lines (34 loc) · 926 Bytes
/
bst.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
-module(bst).
-compile(export_all).
% bst_create(), bst_insert(Bst, N), and bst_search(Bst,N) are copied from
% https://gist.github.com/vedantk/1432100
% the rest is my own implementation
bst_create() -> [].
bst_insert(Bst, [H|T]) -> bst_insert(bst_insert(Bst, H), T);
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.
invert(Bst) ->
case Bst of
[] -> [];
[N, [], []] -> [N, [], []];
[Root, Lhs, Rhs] -> [Root, invert(Rhs), invert(Lhs)]
end.
%need to write a method for balancing the tree