Search code examples
prologsizenodes

prolog need to compute the tree size


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.

Solution

  • 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).