fork download
  1. % 4.13 (**) Layout a binary tree (1)
  2. %
  3. % Given a binary tree as the usual Prolog term t(X,L,R) (or nil).
  4. % As a preparation for drawing the tree, a layout algorithm is
  5. % required to determine the position of each node in a rectangular
  6. % grid. Several layout methods are conceivable, one of them is
  7. % the following:
  8. %
  9. % The position of a node v is obtained by the following two rules:
  10. % x(v) is equal to the position of the node v in the inorder sequence
  11. % y(v) is equal to the depth of the node v in the tree
  12. %
  13. % In order to store the position of the nodes, we extend the Prolog
  14. % term representing a node (and its successors) as follows:
  15. % nil represents the empty tree (as usual)
  16. % t(W,X,Y,L,R) represents a (non-empty) binary tree with root
  17. % W positionned at (X,Y), and subtrees L and R
  18. %
  19. % Write a predicate layout_binary_tree/2:
  20.  
  21. % layout_binary_tree(T,PT) :- PT is the "positionned" binary
  22. % tree obtained from the binary tree T. (+,?) or (?,+)
  23.  
  24. :- ensure_loaded(p4_04). % for test
  25.  
  26. layout_binary_tree(T,PT) :- layout_binary_tree(T,PT,1,_,1).
  27.  
  28. % layout_binary_tree(T,PT,In,Out,D) :- T and PT as in layout_binary_tree/2;
  29. % In is the position in the inorder sequence where the tree T (or PT)
  30. % begins, Out is the position after the last node of T (or PT) in the
  31. % inorder sequence. D is the depth of the root of T (or PT).
  32. % (+,?,+,?,+) or (?,+,+,?,+)
  33.  
  34. layout_binary_tree(nil,nil,I,I,_).
  35. layout_binary_tree(t(W,L,R),t(W,X,Y,PL,PR),Iin,Iout,Y) :-
  36. Y1 is Y + 1,
  37. layout_binary_tree(L,PL,Iin,X,Y1),
  38. X1 is X + 1,
  39. layout_binary_tree(R,PR,X1,Iout,Y1).
  40.  
  41. % Test (see example given in the problem description):
  42. % ?- construct([n,k,m,c,a,h,g,e,u,p,s,q],T),layout_binary_tree(T,PT).
  43.  
Success #stdin #stdout 0s 4504KB
stdin
construct([n,k,m,c,a,h,g,e,u,p,s,q],T),layout_binary_tree(T,PT).
stdout
GNU Prolog 1.4.5 (64 bits)
Compiled Feb  5 2017, 10:30:08 with gcc
By Daniel Diaz
Copyright (C) 1999-2016 Daniel Diaz
| ?- 
uncaught exception: error(existence_error(procedure,construct/2),top_level/0)
| ?-