Advertisement
Coriic

Untitled

Nov 9th, 2017
388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 2.06 KB | None | 0 0
  1. -module(tree).
  2. -export([insert/2, generate_random_tree/2, list_to_tree/1, tree_to_list_pre/1, tree_to_list_in/1, tree_to_list_post/1, search/2, search_ex/2]).
  3.  
  4. -import(rand, [uniform/1]).
  5.  
  6. insert(nil, Value) -> {Value, nil, nil};
  7. insert({Node_Value, Left, Right}, Value) when Value < Node_Value ->
  8.   {Node_Value, insert(Left, Value), Right};
  9. insert({Node_Value, Left, Right}, Value) ->
  10.   {Node_Value, Left, insert(Right, Value)}.
  11.  
  12. generate_random_tree(Tree, 0, _) -> Tree;
  13. generate_random_tree(Tree, N, M) ->
  14.   generate_random_tree(insert(Tree, rand:uniform(M)), N-1, M).
  15.  
  16. generate_random_tree(N, M) -> generate_random_tree(nil, N, M).
  17.  
  18. list_to_tree([], Tree) -> Tree;
  19. list_to_tree([H|T], Tree) ->
  20.   list_to_tree(T, insert(Tree, H)).
  21.  
  22. list_to_tree(L) -> list_to_tree(L, nil).
  23.  
  24. tree_to_list_pre(nil, L) -> L;
  25. tree_to_list_pre({Value, nil, nil}, L) ->
  26.   L ++ [Value];
  27. tree_to_list_pre({Value, Left, Right}, L) ->
  28.   [Value] ++ tree_to_list_pre(Left, L) ++ tree_to_list_pre(Right, L).
  29.  
  30. tree_to_list_pre(Tree) -> tree_to_list_pre(Tree, []).
  31.  
  32. tree_to_list_in(nil, L) -> L;
  33. tree_to_list_in({Value, nil, nil}, L) ->
  34.   L ++ [Value];
  35. tree_to_list_in({Value, Left, Right}, L) ->
  36.   tree_to_list_in(Left, L) ++ [Value] ++ tree_to_list_in(Right, L).
  37.  
  38. tree_to_list_in(Tree) -> tree_to_list_in(Tree, []).
  39.  
  40. tree_to_list_post(nil, L) -> L;
  41. tree_to_list_post({Value, nil, nil}, L) ->
  42.   L ++ [Value];
  43. tree_to_list_post({Value, Left, Right}, L) ->
  44.   tree_to_list_post(Left, L) ++ tree_to_list_post(Right, L) ++ [Value].
  45.  
  46. tree_to_list_post(Tree) -> tree_to_list_post(Tree, []).
  47.  
  48. search(nil, _) -> false;
  49. search({Node_Value, Left, _}, Value) when Value < Node_Value ->
  50.   search(Left, Value);
  51. search({Node_Value, _, Right}, Value) when Value > Node_Value ->
  52.   search(Right, Value);
  53. search(_, _) -> true.
  54.  
  55. search_ex(nil, _) -> throw("Not found");
  56. search_ex({Node_Value, Left, _}, Value) when Value < Node_Value ->
  57.   search_ex(Left, Value);
  58. search_ex({Node_Value, _, Right}, Value) when Value > Node_Value ->
  59.   search_ex(Right, Value);
  60. search_ex(_, _) -> throw("Found!").
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement