【问题标题】:Binary Tree counting nodes in prologprolog中的二叉树计数节点
【发布时间】:2015-02-02 04:17:57
【问题描述】:

我构建了具有 bt(Data,LeftTree,RightTree) 结构的二叉树。

btree(nil).
btree(bt(_,L,R)) :- btree(L), btree(R).

然后我想定义谓词 count1Child(Tree, Count) 断言 Count 是树中具有一个孩子的节点数。我知道如何计算树中节点的总数。但不知道只有一个孩子的节点数。

【问题讨论】:

  • 请举例说明“计算只有一个孩子的节点”是什么意思
  • 例如,bt(1,bt(2,nil,bt(3,nil,nil)),bt(nil)))。 1 和 2 是只有一个孩子的节点。

标签: prolog


【解决方案1】:

在开始编写谓词之前,让我们尝试定义一个谓词,为要计数的节点提供true,为仍然可能出现但不计数的节点提供false。通过这种方式,我们也隐含地定义了我们想要的东西。我假设您只需要具有两个子树的节点。

singlechild_t(nil, false).
singlechild_t(bt(_,nil,bt(_,_,_)), true).
singlechild_t(bt(_,bt(_,_,_),nil), true).
singlechild_t(bt(_,nil,nil), false).
singlechild_t(bt(_,bt(_,_,_),bt(_,_,_)), false).


tree_count(P_2, T, N) :-
   tree_count(P_2, T, 0,N).

tree_count(_, nil, N,N).
tree_count(P_2, T, N0,N) :-
   T = bt(_,L,R),
   if_(call(P_2, T), A = 1, A = 0),
   N1 is N0+A,
   tree_count(P_2, L, N1,N2),
   tree_count(P_2, R, N2,N).

 tree_countsingles(T, N) :-
    tree_count(singlechild_t, T, N).

(使用if_/3

【讨论】:

  • 我明白了,但是 (if_/3) 会导致除 nil 之外的每棵树都出现错误。我会努力解决的。
  • @bbbBB:您需要点击上面的链接并包含if_/3的定义。
【解决方案2】:
cbt(nil, 0).
cbt(bt(_,L,R), T) :- cbt(L,Nl),cbt(R,Nr),
    ( (L=nil,R\=nil ; L\=nil,R=nil) -> C = 1 ; C = 0 ),
    T is Nl + Nr + C.

但您在问题中给出的测试树似乎无效:我测试过

?- cbt(bt(1,bt(2,nil,bt(3,nil,nil)),nil),N).
N = 2.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多