prolog need to compute the tree size

2019-08-06 03:13发布

问题:

I need to get the size of a tree using: size(Tree,Size)

What I have so far is wrong, please advise!

size(empty, Size).
size(tree(L, _, R), Size) :-
    size(L, Left_Size),
    size(R, Right_Size),
    Size is
        Left_Size + Right_Size + 1.

Output should produce:

?- size(node(1,2),X).
X = 2.
?- size(node(1,[2,3,4]),X).
X = 2.
?- size(node(node(a,b),[2,3,4]),X).
X = 3.

回答1:

Prolog is a declarative language, you must state correctly your patterns:

size(node(L,R), Size) :- ... % why you add 1 to left+right sizes ?

From the samples, I suggest to stop the recursion with Size = 1 when anything that is not a node is seen:

size(node(L,R), Size) :- !, ...
size(_, 1).


回答2:

size_tree(nil, 0). % nil simulates a null node

size_tree(node(Root,Left,Right), Size):-

 Root\= nil,
 RootSize = 1,
 size_tree(Left, LeftSide),
 size_tree(Right, RightSide),
 Size is (RootSize + LeftSide + RightSide).