If I have a tree that for example looks like this:
tree3(b(l(1),b(l(2),l(3)))).
How would I write a program that counts the number of leaves? I want it to look something like this when it's been used:
?- tree3(T), count_lea开发者_如何转开发ves(T, N).
N = 3,
T = b(l(1),b(l(2),l(3)))
I'd love any help!
You could do it like this:
count_leaves(l(_), 1).
count_leaves(b(B1, B2), N) :- count_leaves(B1, N1), count_leaves(B2, N2), N is N1 + N2.
Basically, tree that is just a leaf has one leaf. If the tree starts with a branch, recurse into both branches and add the results.
Your solution gives you no
, because nothing will match against empty
. And even if you fixed that, you wouldn't be counting leaves, but inner nodes.
精彩评论