【问题标题】:Finding the binary tree height using Prolog使用 Prolog 查找二叉树高度
【发布时间】:2014-11-22 23:39:39
【问题描述】:

我正在尝试编写二叉树高度问题,但 Prolog 返回 false 而不是高度值。

我的代码是:

height( nil, 0 ).
height( t(_,L, R), H ):-
   (  height(L,_)>height(R,_), height(L,H-1)
   ;  height(R,_)>=height(L,_),height(R,H-1)
   ).

返回 false 而不是 1 的简单示例代码是:

height(t(a,nil,nil),RES).

谢谢。

【问题讨论】:

  • > 和 >= 只需要算术表达式。那应该会产生一个干净的错误。而H-1 是一个术语而不是一个表达式......

标签: prolog logic


【解决方案1】:

height 不是返回高度的函数。当第二个参数是第一个参数的高度时,predicate 为真。所以你可以使用height(L,_) > height(R,_)。您必须执行height(L,LH), height(R,RH) 并将LH 与RH 进行比较。出于类似的原因,您无法查询height(L, H-1) 并获得预期结果,因为正如@false 指出的那样,H-1 在此上下文中是术语'-'(H,1),并且不被解释为算术表达式。在 Prolog 中,算术表达式仅在其位于 is 表达式的右侧或在算术比较表达式中时才会被解释。

因此,您更正的谓词如下所示:

height( nil, 0 ).         % Height of nil tree is 0
height( t(_,L,R), H ) :-  % Height of binary tree t(_,L,R) is H if...
   height(L, LH),         % LH is the height of subtree L, and
   height(R, RH),         % RH is the height of subtree H, and
   (  LH > RH             % if LH > RH, then
   -> H is LH + 1         %   H is LH + 1
   ;  H is RH + 1         % otherwise, H is RH + 1
   ).

或者更直接地,您可以使用 Prolog 中提供的max 函数(正如@false 指出的那样):

height( nil, 0 ).         % Height of nil tree is 0
height( t(_,L,R), H ) :-  % Height of binary tree t(_,L,R) is H if...
   height(L, LH),         % LH is the height of subtree L, and
   height(R, RH),         % RH is the height of subtree H, and
   H is max(LH, RH) + 1.

再次注意,is 右侧的表达式将由 Prolog 求值。

【讨论】:

  • 如果我们想找到树的大小会怎样?会不会像:size(nil, 0). size(t(L,X,R) :- size(L, XL), size(R, XR), X is XL + XR + 1.我是对的还是错的?:)
  • @jake-ferguson 看起来不错。我不会称它为size,因为这有点含糊。我会称之为node_count,或者更好的是binary_tree_node_count。
猜你喜欢
  • 1970-01-01
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-01
  • 2021-09-07
相关资源
最近更新 更多