Prolog - Balanced tree or not

孤街醉人 提交于 2019-12-24 05:03:03

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/7307435/prolog-balanced-tree-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!