Prolog:建立一个完全平衡的树

时间:2011-01-06 15:22:40

标签: prolog

有没有人知道在Prolog中构建完全平衡树的任何简单方法?

这是我找到的一个解决方案,但我想知道是否有人知道任何更简单的解决方案?

这个很简单,但是我花了一点时间来准确掌握它是如何工作的。

谢谢:)。

% from given solution

cbal_tree( 0, nil ) :- !.
cbal_tree( N, t(x,L,R) ) :- 
    N > 0,

    N0 is N - 1, % if N is 4, this would be 3

    N1 is N0 mod 2, % if N is 4, this would be 3 mod 2 = 1
    N2 is N0 - N1, % if N is 4, this would be 3-1= 2

    distrib( N1, N2, LeftNode, RightNode ),

    cbal_tree( LeftNode, L ), 
    cbal_tree( RightNode, R ).

distrib(N,N,N,N) :- !.
distrib(N1,N2,N1,N2). % giving these two clauses (*) 1,2,?,? could give 1,2 or 2,1
distrib(N1,N2,N2,N1). % (*)

2 个答案:

答案 0 :(得分:1)

The accepted answer is wrong.

Consider the case when N=5. The one subtree takes as argument the number 4 and the other the number 0. That is not a balanced tree.

Instead, I propose the following code:

cbal_tree(0, nil).
cbal_tree(N, t(x,L,R)) :-
    N > 0,
    N0 is N - 1,    % -1 to account for root node
    N1 is N0 div 2,
    N2 is N0 - N1,
    (N mod 2 =\= 0 -> permutation([N1,N2], [NLeft,NRight]) ;
                      [N1, N2] = [NLeft, NRight]),
    cbal_tree(NLeft, L),
    cbal_tree(NRight, R).

The if statement is to prevent backtracking from bringing you duplicate answers.

Please consider heavily marking this as an accepted answer because the answer provided is confusing at least.

答案 1 :(得分:0)

这构建对称树:

symm_tree(nil,0).
symm_tree(t(L,R),Level) :-
    Level > 0,
    M is Level-1,
    symm_tree(L,M),
    symm_tree(R,M).

向节点添加标签应该是微不足道的。

您发布的代码可以略微简化为

cbal_tree(0, nil).
cbal_tree(N, t(x,L,R)) :- 
    N > 0,
    N0 is N - 1,    % -1 to account for root node
    N1 is N0 mod 2,
    N2 is N0 - N1,

    permutation([N1,N2], [NLeft,NRight]),

    cbal_tree(NLeft, L),
    cbal_tree(NRight, R).

但这实际上是多么简单,并且distrib/3重复项的处理已经消失。

相关问题