Advertisement
Guest User

Untitled

a guest
Jan 24th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.07 KB | None | 0 0
  1. ----------------------
  2. Check if a tree is BST
  3. ----------------------
  4.  
  5. checkIfBST(t(_, nil, nil)).
  6.  
  7. checkIfBST(t(Key, t(LKey, LLT, LRT), nil)):-
  8.     Key > LKey,
  9.     checkIfBST(t(LKey, LLT, LRT)).
  10.  
  11. checkIfBST(t(Key, t(RKey, RLT, RRT))):-
  12.     Key > RKey,
  13.     checkIfBST(t(RKey, RLT, RRT)).
  14.  
  15. checkIfBST(t(Key, t(LKey, LLT, LRT), t(RKey, RLT, RRT))):-
  16.     Key > LKey,
  17.     Key < RKey,
  18.     checkIfBST(t(LKey, LLT, LRT)),
  19.     checkIfBST(t(RKey, RLT, RRT)).
  20.  
  21.  
  22. -------------------
  23. BUILD BST FROM LIST
  24. -------------------
  25.  
  26. addTree(A, t(Key, nil, R), t(Key, t(A, nil, nil), R)):-
  27.     A < Key, !.
  28.  
  29. addTree(A, t(Key, L, nil), t(Key, L, t(A, nil, nil))):-
  30.     A > Key, !.
  31.  
  32. addTree(A, t(Key, L, R), t(Key, NL, R)):-
  33.     A < Key, !,
  34.     addTree(A, L, NL).
  35.  
  36. addTree(A, t(Key, L, R), t(Key, L, NR)):-
  37.     A > Key, !,
  38.     addTree(A, R, NR).
  39.  
  40. buildBST(L, R):-
  41.     buildBST(L, [], R).
  42.  
  43. buildBST([], R, R).
  44.  
  45. buildBST([H|T], [], R):-
  46.     buildBST(T, t(H, nil, nil), R).
  47.  
  48. buildBST([H|T], t(X, L, R), Res):-
  49.     addTree(H, t(X, L, R), Res1),
  50.     buildBST(T, Res1, Res).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement