开发者

Prolog - Balanced tree or not

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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜