Hello. Tell me, please, how to find in the tree the number of branches from the root to the given vertex.

Used tree:

( 3 ) / \ / \ ( 2 ) ( 5 ) / \ \ / \ \ ( 1 ) ( 2 ) ( 8 ) / / ( 9 ) 

Recursive tree pass code:

  domains treetype = tree(integer, treetype, treetype); empty() predicates traverse(treetype) clauses traverse(empty). traverse(tree(Name, Left, Right)) :- write(Name,'\n'), traverse(Left), traverse(Right). goal traverse(tree(3, tree(2, tree(1, empty, empty), tree(2, empty, empty)), tree(5, empty, tree(8, tree(9, empty, empty), empty)))). 

You need to somehow add the code so that it can count the number of branches. For example, between point 3 and 9, the result should be output 3. Between 3 and 8, the result should display 2.

Thank you in advance.

  • And what version of the prologue? - insolor
  • I program on Visual Prolog 5.2. - Draculidze
  • one
    It seems to work in the turbo prologue, see what you can do. - insolor
  • Thank you very much :) You can in the turbo prologue. I ’ll install that if it is :) - Draculidze

1 answer 1

It seems to work. In branch, the first parameter is the desired number, the second is a tree. If the number is found, displays the length of the path to it from the root. If not found, write the number such and such not found. Made in turbo prolog, but in theory should work in visual prolog.

 domains treetype = tree(integer, treetype, treetype); empty() predicates traverse(treetype) nondeterm br(integer,integer,treetype) nondeterm branch(integer,treetype) clauses traverse(empty). traverse(tree(Name, Left, Right)):- write(Name,'\n'), traverse(Left), traverse(Right). br(_,_,empty):-fail. br(X,Y,tree(X,Left,Right)):-write(Y). br(X,Y,tree(_,Left,Right)):-Y1=Y+1, br(X,Y1,Left). br(X,Y,tree(_,Left,Right)):-Y1=Y+1, br(X,Y1,Right). branch(X,Tree):-br(X,0,Tree);write(X," not found\n"). goal branch(8,tree(3, tree(2, tree(1,empty,empty), tree(2,empty,empty)), tree(5, empty, tree(8, tree(9,empty,empty), empty)))). 
  • Thank you very much :) Two errors are displayed, but they are easily corrected. For this you need: In the predicates, replace the following lines: br (integer, integer, treetype) branch (integer, treetype) with these: nondeterm br (integer, integer, treetype) nondeterm branch (integer, treetype) - Draculidze
  • Corrected. And what does nondeterm mean by the way? and what were the mistakes? - insolor
  • in Turbo Prolog all nondeterm predicates, i.e. backtracking works in them. And in Visual Prolog, backtracking does not work in default predicates. In my humble opinion, this violates the purity of the idea - renegator
  • Yeah, I see. Just neither with Turbo, nor with Visual did not face earlier. - insolor