prolog是树平衡的

时间:2015-06-04 11:15:28

标签: tree prolog balance

我需要实现一个谓词isBalanced/1,如果isBalanced(T)是一个平衡的树,T为真。

在这种情况下,二叉树由结构节点(左,右)定义,其中左侧和右侧可以是另一个节点或任何Prolog数据项。

到目前为止我所拥有的:

height(node(L,R), Size) :-
    height(L, Left_Size),
    height(R, Right_Size),
    Size is Left_Size + Right_Size + 1 .
height(l(_),1).

isBalanced(l(_)).
isBalanced(node(B1,B2)):-
    height(B1,H1),
    height(B2,H2),
    abs(H1-H2) =< 1,
    isBalanced(B1),
    isBalanced(B2).

预期产出:

?- isBalanced(1).
true.
?- isBalanced(node(1,2)).
true.
?- isBalanced(node(1,node(1,node(1,2)))).
false.

它无效,任何建议都将不胜感激!

1 个答案:

答案 0 :(得分:1)

你如何代表你的树?它在我看来

  • l(_)代表空树,
  • node(L,R)代表非空树。

我怀疑你的height/2有一个错误,你似乎已经将空树的高度定义为1(而不是0)。

我可能会代表一个二叉树,如下所示:

  • nil - 空树
  • tree(D,L,R) - 非空树,其中

    • D:有效负载数据
    • L:left subtree
    • R:右子树

以便可以代表树

    a
   / \
  b   c   
 /   / \
d   e   f

作为

tree( a ,
  tree( b ,
    tree( d , nil , nil ) ,
    nil
  ) ,
  tree( c ,
    tree( e , nil , nil ) ,
    tree( f , nil , nil ) 
) .

和叶节点(没有子树的树)看起来像

tree( data , nil , nil )

确定余额

因此,从该表示和定义

开始工作
  

如果符合以下条件,二叉树就会平衡:

     
      
  • 它的左子树是平衡的
  •   
  • 它的右子树是平衡的
  •   
  • 子树的相应高度相差不超过1
  •   

我们可以轻松地为问题编写描述性解决方案:

is_balanced( nil         ) .  % the empty tree is balanced
is_balanced( tree(_,L,R) ) :- % a non-empty tree is balanced IF ...
  is_balanced(L) ,            % - the left sub-tree is balanced
  is_balanced(R) ,            % - the right sub-tree is balanced
  tree_height(L,LH) ,         % - the height of the left sub-tree
  tree_height(R,RH) ,         % - the height of the right sub-tree
  abs( LH - RH ) < 2          % - differ by no more than 1
  .                           % Right?

我们只需要计算树的高度。

计算身高

可以按如下方式计算这种树的高度:

tree_height( nil         , 0 ) .  % the depth of an empty tree is zero.
tree_height( tree(_,L,R) , H ) :- % for a non-empty tree...
  tree_height( L , LH ) ,         % - we compute the height of the left subtree
  tree_height( R , RH ) ,         % - we compute the height of the right subtree
  H is 1 + max( LH , RH )         % - the overall height is 1 more than the higher of the two values thus obtained.
  .                               % Right?

<强>效率

有人可能会注意到

  • 似乎发生了很多树遍历,
  • is_balanced/2与<{1}}有可疑的相似性

因此,人们可以通过混合两者并在运行中计算深度来优化事物:

已编辑:已添加包装谓词tree_height/2

is_balanced/1
相关问题