prolog - 查找二叉树的最大和子树

时间:2016-09-02 14:24:28

标签: prolog

如何在Prolog中找到二叉树的最大 sum 子树

让我们说这是树:

t(t(t(nil,-5,nil),4,t(t(nil,15,nil),-20,t(nil,10,nil))),2,t(nil,-8,t(t(nil,9,nil),12,t(nil,10,nil))))

此树的最大 sum 子树是右下树:

t(t(nil,9,nil),12,t(nil,10,nil))

我怎样才能在prolog中找到这个?

2 个答案:

答案 0 :(得分:2)

你可以这样写:

 max_sub_tree(Tree,T,N):-
    sol_tree_noroot(Tree,T1,N1),
    sol_tree_withroot(Tree,T2,N2),!,
    max_set(T1,N1,T2,N2,T,N).

max_set(T1, N1, T2, N2, T, N) :-
    (N1>N2,T=T1,N=N1;
     N2>N1,T=T2,N=N2;
    N2=:=N1,N=N1,(T=T1;T=T2)).    

sol_tree_noroot(nil,nil,0).
sol_tree_noroot(t(L,_,R),T,N):-
      max_sub_tree(L,T1,N1),max_sub_tree(R,T2,N2),!,
      max_set(T1, N1, T2, N2, T, N).

sol_tree_withroot(nil,nil,0).
sol_tree_withroot(t(L,X,R),t(L1,X,R1),N3):-
     sol_tree_withroot(L,T1,N1),sol_tree_withroot(R,T2,N2),
     max_set2(T1,N1,T2,N2,L1,R1,N),
     N3 is N+X.

max_set2(T1,N1,T2,N2,L,R,N):-
    (N1>0,N2>0,N is N1+N2,L=T1,R=T2;
     N1>=0,N2<0,N is N1 ,R=nil,L=T1;
     N1<0,N2>=0,N is N2 ,L=nil,R=T2;
     N1<0,N2<0,N1<N2,N is N2 ,L=nil,R=T2;
     N1<0,N2<0,N1>N2,N is N1 ,L=T1,R=nil;
     N1>0,N2=0,N is N1,(L=T1,R=nil;L=T1,R=T2);
     N1=0,N2>0,N is N2,(R=T2,L=nil;L=T1,R=T2);
     N1=0,N2=0,N is N1,(L=T1,R=nil;R=T2,L=T1;L=T1,R=T2)). 

致电时:

max_sub_tree(t(t(t(nil, -5, nil), 4, t(t(nil, 15, nil), -20, t(nil, 10, nil))), 2, t(nil, -8, t(t(nil, 9, nil),12,t(nil, 10, nil)))),T,N).

它返回:

T = t(t(nil, 4, t(t(nil, 15, nil), -20, t(nil, 10, nil))), 2, t(nil, -8, t(t(nil, 9, nil), 12, t(nil, 10, nil)))),
N = 34 ;

其中T是给定树中的最大子树,其中包含节点34的总和(而不是示例中的31)。

答案 1 :(得分:1)

... Mmmmhhhh 不确定是什么意思和#34; max sum subtree&#34;但是......希望这会有所帮助

maxSubTree(nil, 0, 0, nil).

maxSubTree(t(T1, V0, T2), Sum, Sum, t(T1, V0, T2)) :-
  maxSubTree(T1, Sum1, MaxSum1, _),
  maxSubTree(T2, Sum2, MaxSum2, _),
  Sum is Sum1 + Sum2 + V0,
  Sum >= MaxSum1,
  Sum >= MaxSum2.

maxSubTree(t(T1, V0, T2), Sum, MaxSum1, MaxTree1) :-
  maxSubTree(T1, Sum1, MaxSum1, MaxTree1),
  maxSubTree(T2, Sum2, MaxSum2, _),
  Sum is Sum1 + Sum2 + V0,
  MaxSum1 >= Sum,
  MaxSum1 >= MaxSum2.

maxSubTree(t(T1, V0, T2), Sum, MaxSum2, MaxTree2) :-
  maxSubTree(T1, Sum1, MaxSum1, _),
  maxSubTree(T2, Sum2, MaxSum2, MaxTree2),
  Sum is Sum1 + Sum2 + V0,
  MaxSum2 >= Sum,
  MaxSum2 >= MaxSum1.

maxSubTree(t(t(t(nil,-5,nil),4,t(t(nil,15,nil),-20,t(nil,10,nil))),2,t(nil,-8,t(t(nil,9,nil),12,t(nil,10,nil)))), _, _, MT)

我获得(变量MT

t(t(nil,9,nil),12,t(nil,10,nil))