2

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.
3
  • What's the algorithm in English, for a start? Commented Jan 22, 2011 at 15:42
  • Well, I need all the leaves to be in the same distance from the root. So the most simple algorithm is going through all of them and check if all have the same distance from the root. Commented Jan 22, 2011 at 16:10
  • Perhaps a slightly quicker approach: Find the depth of one leaf, then look for a leaf node that has less depth or a non-leaf node that has an equal depth. If you find either of those, the binary tree is not "complete". Commented Jan 22, 2011 at 21:25

1 Answer 1

3
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.
Sign up to request clarification or add additional context in comments.

2 Comments

It doesn't work. It returns true for all the examples I showed above. If I understood what you have tried to do is to check that the right sub-tree and left sub-tree has the same height which doesn't define a complete binary tree.
@user550413: has you actually tried it? because it works with me, at least for the samples in your post!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.