Question

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).
Was it helpful?

Solution

H + 1 is not evaluated to the value of H plus one if you don't tell Prolog to do arithmetic evaluation; instead, Prolog builds a term with + as the functor and H and 1 as the arguments. (Try H + 1 =.. L and check the value of L to convince yourself of this fact.)

Do something like

height(B1, H1),
height(B2, H2),
abs(H1 - H2) =< 1.

=< will perform arithmetic evaluation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top