Search code examples
treeprologpostorder

Prolog Postorder Traversal in a general tree using univ


I am trying to traverse a general tree in prolog in a postorder way. I found a lot of binary tree postorder traversals but could not use them to my purpose. I wrote a program but it only prints my tree in the reverse way of how it is entered, ie for input

?-postorder(a(b,c,d(e,f,g))).
->g f e d c b a true (is what I get)
->b c e f g d a true (what i want to get)

Here is the code i have managed to write till now

postorder([]).
postorder(List):- List =..X , myfun(X).
myfun([A|B]):- atom(A), myfun(B),write(A),write(' ').
myfun([A|B]):- postorder(A),myfun(B).
myfun([]).

I am not getting a way for postorder traversal
Any help is much appreciated


Solution

  • Here is the solution that works just fine for me.

    postorder([]).
    postorder(Tree):- Tree =..[Parent|Children] , myfun(Children), write(Parent),write(' ').
    myfun([First|Next]):- atom(First), write(First), write(' '), myfun(Next).
    myfun([First|Next]):- postorder(First),myfun(Next).
    myfun([]).