Prolog-是否平衡树 [英] Prolog - Balanced tree or not
本文介绍了Prolog-是否平衡树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个程序,告诉我一棵树是否平衡.在这种情况下,平衡意味着相同的高度或高度差为1.
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.
这是我到目前为止编写的内容,但是对于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
不会被评估为H
的值,如果您不告诉Prolog进行算术评估,则不会加一.相反,Prolog用+
作为函子,并用H
和1
作为自变量构建一个术语. (尝试H + 1 =.. L
并检查L
的值以使自己相信这一事实.)
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.)
做类似的事情
height(B1, H1),
height(B2, H2),
abs(H1 - H2) =< 1.
=<
将执行算术评估.
这篇关于Prolog-是否平衡树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文