Skip to content

Instantly share code, notes, and snippets.

@pjrt
Created April 2, 2016 00:44
Show Gist options
  • Save pjrt/04e7d67e6ec89c140f3768dd9bc24999 to your computer and use it in GitHub Desktop.
Save pjrt/04e7d67e6ec89c140f3768dd9bc24999 to your computer and use it in GitHub Desktop.
{-# LANGUAGE MultiWayIf #-}
-- http://codercareer.blogspot.com/2013/03/no-46-nodes-with-sum-in-binary-search.html
data Tree a = Leaf a | Branch a (Tree a) (Tree a)
deriving Show
getValue (Leaf v) = v
getValue (Branch v _ _) = v
type Path a = [a]
findSum :: (Num a, Ord a) => a -> Tree a -> [Path a]
findSum s = fs 0 []
where
fs prevSum path tree =
let v = getValue tree
newSum = prevSum + v
newPath = path ++ [v]
in if | newSum == s -> [newPath] -- if the new sum matches, we are done
| newSum > s -> [] -- invalid, the sum went over
| newSum < s ->
case tree of
Leaf v -> [] -- we reached a leaf, we are done
Branch v l r -> fs newSum newPath l ++ fs newSum newPath r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment