Tree 树的高度-序言

Tree 树的高度-序言,tree,prolog,height,binary-tree,Tree,Prolog,Height,Binary Tree,我试图在Prolog中编写一个谓词来查找树的高度 我的树是这样表示的: A / \ B C / \ / \ D E F G [a[b[d,e],c[f,g]]([Root[Children]])) 我的谓词是: height(Tr,0) :- atomic(Tr). height([L|R],N) :- height(L,N1), heig

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

我的树是这样表示的:

             A
           /    \
          B      C
         / \    / \
        D   E  F   G
[a[b[d,e],c[f,g]]([Root[Children]]))

我的谓词是:

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
    表示
  • 非空树由结构
    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元树的深度(其中每个节点可以有任意数量的子节点)并不复杂。我们将这样表示我们的n元树:

  • 空树再次由原子
    nil
    表示
  • 非空树由结构
    树/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.
  .

您的查询似乎不代表有效的树,该树应始终具有形状
[\uu,子列表]
。此代码段采用这种表示形式,并且库()可用:

屈服

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

在哪个维度中不工作?树表示形式看起来不一致,并且您的代码与有效树不匹配(不管它看起来像什么-很难说它是什么)。例如,
[c,e,f]
看起来不像是基于图片的有效子树。如果这不是您的树的外观,那么请显示您测试的实际树,并解释代码不起作用的含义。我认为,首先,您需要定义一致的树表示<代码>[a[b,d],[c,e,f]](由3个元素组成的列表)不能完全描述您所画的树,并且它与您给出的
[Root,[Children]]
(由2个元素组成的列表)的一般模式不匹配。一旦有了一致的表示,代码就会变得简单明了。对不起,我犯了一个错误。。。现在我有一个一致的树表示,但高度不好:/n您的新树表示仍然不一致。如果
[a[b[d,e],c[f,g]]
是一个二叉树,那么内部列表
[b[d,e],c[f,g]
的元素太多。表示应该有一个清晰的head、left、right结构,然后谓词就可以跟随该结构。现在,您的谓词有
[L | R]
,其中
L
是列表头,
R
是列表尾(列表的其余部分),这似乎不正确。人们会期望在实现中左右对称。
?- height([a,[ [b,[d,e]], [c,[f,g]] ]],N).
N = 2.