3

I need to implement a predicate trav(Tree,List) that performs a left to right tree traversal;

Where: Tree is defined by the structure node(left,right), where left and right can be either another node or any Prolog data item. List is the list of leaf node values in the tree.

For example:

?- trav(x,L).
L = [x].
?- trav(node(1,node(2,node(a,b))),L).
L = [1, 2, a, b] .

What I have so far:

trav(tree,[ ]).
trav(node(Left,Rigth), L) :-
    trav(Left, L),
    trav(Right, L),
    append(Left,[Left|Right],L).
false
  • 10,264
  • 13
  • 101
  • 209
Zast
  • 492
  • 2
  • 7
  • 22
  • You have again a problem with what you want a tree to be! Define **first** a predicate `is_tree/1` that states what a tree is in you opinion. It is *very* uncommon, but certainly possible to have nodes without elements. Such nodes typically occur for expression-trees. But otherwise they do not occur. – false Jun 07 '15 at 07:59
  • Not my opinion, it is what I was given to work with. – Zast Jun 07 '15 at 09:08

1 Answers1

2

My Prolog is slightly rusty, but I believe that this should do it:

node(Left, Right).

trav(node(Left, Right), L) :- 
  trav(Left, L1), 
  trav(Right, L2),
  append(L1, L2, L).
trav(X, [X]) :- X \= node(A, B).

Intuitively, trav(Left, L1) says traverse the left subtree, storing each element in L1. trav(Right, L2) says traverse the right subtree storing each element in L2. Lastly, append(L1, L2, L) append the two lists, L1 and L2 into list L. For a leaf, trav(X, [X]), puts X into a singleton list as long as it does not unify with a node.

Matt
  • 4,029
  • 3
  • 20
  • 37
  • Is it correct to stop it after it prints the first line, if so how or where do you place the cut? `1 ?- trav(node(1,node(2,node(a,b))),L). L = [1, 2, a, b] ; L = [1, 2, node(a, b)] ; L = [1, node(2, node(a, b))] ; L = [node(1, node(2, node(a, b)))].` – Zast Jun 07 '15 at 03:25
  • 2
    Is it OK to explicitly annotate the leaves of the tree? So, your query would look more like: `trav(node(leaf(1),node(leaf(2),node(leaf(a),leaf(b)))),L).` This will only have one solution in my edited answer. – Matt Jun 07 '15 at 03:41
  • The examples that I provided above are what will be used! – Zast Jun 07 '15 at 03:58
  • OK @user3633383, this should do it – Matt Jun 07 '15 at 04:02