Reputation: 4819
What is the algorithm of checking if a Binary tree is a complete binary tree? (Using Prolog).
For example:
?- complete(nil).
true.
?- complete(tree(1,nil,nil)).
true.
?- complete(tree(1,tree(2,nil,nil),nil)).
false.
?- complete(tree(1,tree(2,nil,nil),tree(3,nil,nil))).
true.
Upvotes: 2
Views: 4160
Reputation: 10244
complete(T) :- complete(T, _).
complete(nil, 0).
complete(tree(_, L, R), N) :-
complete(L, N1),
complete(R, N1),
N is N1 + 1.
update:
It works for me:
?- complete(nil).
true.
?- complete(tree(1,nil,nil)).
true.
?- complete(tree(1,tree(2,nil,nil),nil)).
false.
?- complete(tree(1,tree(2,nil,nil),tree(3,nil,nil))).
true.
Upvotes: 3