Reputation: 11
I'm very new to Prolog, and trying to find an element to search in binary tree, it finds it successfully but the problem is if it doesn't it still gives yes, I want it to say no or to say not found. My code is:
child(1,2,3).
child(2,4,5).
child(3,6,7).
node(1,a).
node(2,b).
node(3,c).
node(4,d).
node(5,f).
node(6,f).
node(7,g).
show(X):-
write('element is found in node: '),write(X),nl.
inc(X,Y,Z):-
Y is X+X,
Z is X+X+1.
find(A):-
traverse3(1,A).
traverse3(X,A):-
check(X,A),
inc(X,Y,Z),
child(X,Y,Z),
traverse3(Y,A),
traverse3(Z,A).
check(X,A):- not(node(X,A)).
check(X,A):-
node(X,A),
show(X).
traverse3(X,A):- not(child(X,Y,Z)).
Upvotes: 1
Views: 706
Reputation:
This is an unusual binary tree. But anyway, since you have already "normalized" it to a database representation, all you have to do to find an element is to ask for it.
In other words, if your program tree.pl
consists only of the child/3
and node/2
facts:
child(1,2,3).
child(2,4,5).
child(3,6,7).
node(1,a).
node(2,b).
node(3,c).
node(4,d).
node(5,f).
node(6,f).
node(7,g).
You can simply query for the element you need:
?- [tree].
true.
?- node(N, a).
N = 1.
?- node(N, f).
N = 5 ;
N = 6.
?- node(4, E).
E = d.
?- node(N, E).
N = 1, E = a ;
N = 2, E = b ;
N = 3, E = c ;
N = 4, E = d ;
N = 5, E = f ;
N = 6, E = f ;
N = 7, E = g.
Or is there something I am missing?
Upvotes: 1