I want to write a program that tells me if a tree is balanced or not. In this case balanced means same height or a height difference of 1.
This is what I've written so far but it doesn't work for the height difference of 1. Why?
balanced(l(_)).
balanced(b(B1, B2)):-
height(B1,H),
height(B2,H),
balanced(B1),
balanced(B2).
balanced(b(B1,B2)):-
height(B1,H + 1),
height(B2,H),
balanced(B1),
balanced(B2).
balanced(b(B1,B2)):-
height(B1,H),
height(B2,H + 1),
balanced(B1),
balanced(B2).
H + 1
is not evaluated to the value ofH
plus one if you don't tell Prolog to do arithmetic evaluation; instead, Prolog builds a term with+
as the functor andH
and1
as the arguments. (TryH + 1 =.. L
and check the value ofL
to convince yourself of this fact.)Do something like
=<
will perform arithmetic evaluation.