I am trying to implement an inorder traversal which in every stage I’ll get the current node.
For example:
?- getnodesinorder(tree(1,nil,nil),X).
X = 1 ;
false.
?- getnodesinorder(tree(5,tree(4,tree(1,nil,tree(3,tree(2,nil,nil),nil)),nil),tree(6,nil,nil)),X).
X = 1 ;
X = 2 ;
X = 3 ;
X = 4 ;
X = 5 ;
X = 6 ;
false.
I’ve tried the next code:
getnodesinorder(tree(CurrentNode,nil,nil), CurrentNode).
getnodesinorder(tree(X, Left, nil), CurrentNode) :-
getnodesinorder(Left, _ ),
CurrentNode is X.
getnodesinorder(tree(X, nil, Right), CurrentNode) :-
CurrentNode is X,
getnodesinorder(Right, _ ).
getnodesinorder(tree(X, Left, Right), CurrentNode) :-
getnodesinorder(Left, _ ),
CurrentNode is X,
getnodesinorder(Right, _ ).
So of course the base (1st example works) but when trying to run the 2nd one I get
X=5;
false
as result. Why is that?
The error occurs because you’re processing the left and right subtrees, but not doing anything with the values in them:
getnodesinorder(Left, _ )just throws them away. So, your predicate only returns the top element.Here’s how you do an in-order traversal:
Example query: