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.
size_tree(nil, 0). % nil simulates a null node
size_tree(node(Root,Left,Right), Size):-
Prolog is a declarative language, you must state correctly your patterns:
From the samples, I suggest to stop the recursion with Size = 1 when anything that is not a node is seen: