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).
My Prolog is slightly rusty, but I believe that this should do it:
Intuitively,
trav(Left, L1)
says traverse the left subtree, storing each element inL1
.trav(Right, L2)
says traverse the right subtree storing each element inL2
. Lastly,append(L1, L2, L)
append the two lists,L1 and L2
into listL
. For a leaf,trav(X, [X])
, putsX
into a singleton list as long as it does not unify with anode
.