一棵树的高度 - PROLOG

Height of a tree - PROLOG

我尝试在 Prolog 中编写一个谓词来查找树的高度。

我的树是这样表示的:

             A
           /    \
          B      C
         / \    / \
        D   E  F   G

[a,[b,[d,e],c[f,g]]]([根,[子]])

我的谓词是:

height(Tr,0) :- 
   atomic(Tr).
height([L|R],N) :- 
   height(L,N1),
   height(R,N2), 
   N is max(N1,N2)+1. 

但是我的代码不起作用。当我写:

height([a,[b,[d,e],c,[f,g]]],N).

N 等于 8。

请问有什么帮助吗?

注意:根的高度从 0 开始。

它有助于找到正确的抽象。

给定一个二叉树,使用这些约定表示:

  • 一个空树由原子nil表示。
  • A non-empty 树 由结构 tree/3 表示,其中
    • 第一个参数是节点的有效载荷,
    • 第二个参数是左子树(负载整理为小于当前节点的节点),
    • 第三个参数是右子树(其有效载荷整理为大于当前节点的节点)

解决方法很简单:

tree_depth( nil         , 0 ) .   % the depth of an empty tree is 0.
tree_depth( tree(_,L,R) , D ) :-  % the depth of a non-empty tree is computed thus:
  tree_depth(L,L1) ,              % - compute the depth of the left subtree
  tree_depth(R,R1) ,              % - compute the depth of the right subtree
  D is 1 + max(L1,R1)             % - the overall depth is 1 more than the maximum depth in both subtrees.
  .                               %

计算 n-ary 树 的深度,其中每个节点可以有任意数量的 children,并不复杂。我们将这样表示我们的 n-ary 树

  • 空树再次用原子nil表示。
  • A non-empty 树 由结构 tree/2 表示,其中
    • 第一个参数是节点的有效负载
    • 第二个参数是包含节点子树的列表(其中任何一个都可能是 nil)。

解决方案也很简单:

tree_depth( nil       , 0 ) .   % the depth of the empty tree is 0.
tree_depth( tree(_,C) , D ) :-  % the depth of a non-empty tree is computed thus:
  subtree_depth( C , 0 , T ) ,  % - compute the depth of the subtrees of the current node
  D is 1+T                      % - add 1 to that
  .                             %

subtree_depth( []     , D , D ) .   % child subtrees exhausted? unify the accumulator with the result
subtree_depth( [X|Xs] , T , D ) :-  % otherwise...
  tree_depth(X,X1) ,                % - compute the depth of the current subtree
  T1 is max(T,X1) ,                 % - set the accumulator the max value
  subtree_depth( Xs , T1 , D )      % - recurse down on the tail.
  .

您的查询似乎没有代表一棵有效的树,它应该总是 具有 [_, SubList] 的形状。此代码段假定这样的表示和库的可用性 (aggregate):

height([_,Sub], Height) :- !,
    aggregate(max(H + 1), S^(member(S, Sub), height(S, H)), Height).
height(_, 0).

产量

?- height([a,[ [b,[d,e]], [c,[f,g]] ]],N).
N = 2.