Difference between revisions of "99 questions/Solutions/61"
< 99 questions | Solutions
Jump to navigation
Jump to search
Line 4: | Line 4: | ||
<haskell> |
<haskell> |
||
− | countLeaves |
+ | countLeaves Empty = 0 |
− | countLeaves (Branch |
+ | countLeaves (Branch _ Empty Empty) = 1 |
− | countLeaves (Branch |
+ | countLeaves (Branch _ Empty r) = countLeaves r |
+ | countLeaves (Branch _ l Empty) = countLeaves l |
||
+ | countLeaves (Branch _ l r) = countLeaves l + countLeaves r |
||
</haskell> |
</haskell> |
Revision as of 20:13, 20 January 2011
Count the leaves of a binary tree
A leaf is a node with no successors. Write a predicate count_leaves/2 to count them.
countLeaves Empty = 0
countLeaves (Branch _ Empty Empty) = 1
countLeaves (Branch _ Empty r) = countLeaves r
countLeaves (Branch _ l Empty) = countLeaves l
countLeaves (Branch _ l r) = countLeaves l + countLeaves r