Binary tree inorder traversal using Prolog
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 ;
fa开发者_C百科lse.
?- 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:
inorder(tree(_,L,_), X) :- inorder(L,X).
inorder(tree(X,_,_), X).
inorder(tree(_,_,R), X) :- inorder(R,X).
Example query:
?- inorder(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.
[test] λ = cat test.pl
append([], Ys, Ys).
append([X|Xs], Ys, [X|Zs]) :- append(Xs, Ys, Zs).
getnodesinorder(nil, []).
getnodesinorder(tree(X, Left, Right), R) :-
getnodesinorder(Left,R1),
getnodesinorder(Right,R2),
append(R1,[X|R2],R).
Works for me
?-getnodesinorder(tree(5,tree(4,tree(1,nil,tree(3,tree(2,nil,nil),nil)),nil),tree(6,nil,nil)),X).
X = [1,2,3,4,5,6] ?
yes
精彩评论