Difference between revisions of "99 questions/Solutions/61A"
< 99 questions | Solutions
Jump to navigation
Jump to search
(categorize) |
|||
(One intermediate revision by one other user not shown) | |||
Line 9: | Line 9: | ||
leaves (Branch a left right) = leaves left ++ leaves right |
leaves (Branch a left right) = leaves left ++ leaves right |
||
</haskell> |
</haskell> |
||
+ | |||
+ | Alternative solution only using cons: |
||
+ | |||
+ | <haskell> |
||
+ | leaves t = leaves' t [] |
||
+ | where leaves' Empty xs = xs |
||
+ | leaves' (Branch x Empty Empty) xs = x:xs |
||
+ | leaves' (Branch _ l r) xs = leaves' l $ leaves' r xs |
||
+ | </haskell> |
||
+ | |||
+ | |||
+ | [[Category:Programming exercise spoilers]] |
Latest revision as of 13:39, 25 December 2016
Collect the leaves of a binary tree in a list
A leaf is a node with no successors. Write a predicate leaves/2 to collect them in a list.
leaves :: Tree a -> [a]
leaves Empty = []
leaves (Branch a Empty Empty) = [a]
leaves (Branch a left right) = leaves left ++ leaves right
Alternative solution only using cons:
leaves t = leaves' t []
where leaves' Empty xs = xs
leaves' (Branch x Empty Empty) xs = x:xs
leaves' (Branch _ l r) xs = leaves' l $ leaves' r xs