Tree traversal refers to the process of visiting each node in a tree data structure in a systematic way. The preorder traversal in the following image
returns F, B, A, D, C, E, G, I, H (root, left, right). This is the Prolog code:
preorder(tree(X,L,R),Xs) :-
preorder(L,Ls),
preorder(R,Rs),
append([X|Ls],Rs,Xs).
preorder(void,[]).
I would write a prolog program that returns
F, B, A, F,B,D, C,F,B,D, E,F, G, I, H
that is, the paths of the tree. Any suggestions?
Try this out for size:
Testing it out with a fact representing the tree from here:
Trying it out (without showing bindings for
T):Note that
dfs_paths/2backtracks to give you the alternate paths. If you wanted a list of them all up front, you could try:If you wanted a flat list of terms as you’ve written above, you can
flatten/2the result.