I need to count all the internal nodes of a binary tree using prolog I can count all of the nodes using the following code
internal(tree(_,L,R), I) :- internal(L, I2), internal(R, I3), I is I2 + I3 + 1.
internal(nil, 0).
And I thought that by changing the base case to
internal(tree(_,nil, nil), 0).
I could get it to work but it returns false.
here is a test case that should return 4 internal(tree(8,tree(5,tree(2,nil,nil),tree(7,nil,nil)), tree(9,nil,tree(15,tree(11,nil,nil),nil))),I).
Could anyone tell me where my mistake is? Thanks
After reading your suggestions I've got this but it still fails.
internal(tree(_,L,R), I) :- internal(L, I2), internal(R, I3), I is I2 + I3.
internal(tree(_,nil, R), I):- !, internal(R, I3), I is I3 + 1.
internal(tree(_,L, nil), I):- !, internal(L, I3), I is I3 + 1.
internal(tree(_,nil, nil), 0).
internal(nil, 0).
+1doing here? - Willem Van Onsemlas result?lis not a variaable, but a constiers.so you should use uppercase v identifiers. - Willem Van Onsemtree(_, nil, tree(_, _, _))in your example. How does this matches the inductive, or base case if you removedinternal(nil, 0)? - Willem Van Onsemtree(_, nil, tree(_, _, _)), then the left child isnil, and the right one atree, so the basecase is not sufficient, nor is the inductive satisfying, since it will callinternal/2in the children, hence it will callinternal(nil, I1). - Willem Van Onsem