Skip to content

Instantly share code, notes, and snippets.

@Cornpop456
Created April 28, 2017 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cornpop456/b1aba0581949418672b1f6f061ab6d04 to your computer and use it in GitHub Desktop.
Save Cornpop456/b1aba0581949418672b1f6f061ab6d04 to your computer and use it in GitHub Desktop.
data Tree a = Leaf | Node (Tree a) a (Tree a) deriving (Show, Eq)
treeTest :: Tree Integer
treeTest = Node (Node Leaf 5 (Node Leaf 4 Leaf)) 10 (Node Leaf 20 (Node Leaf 50 (Node Leaf 100 Leaf)))
treeSum :: Tree Integer -> Integer
treeSum tree | tree == Leaf = error "Empty tree!"
| otherwise = helper 0 tree where
helper acc (Node f d s) | (f == Leaf && s == Leaf) = acc + d
| (f /= Leaf && s /= Leaf) = (helper (acc + d) f) + (helper acc s)
| (f/=Leaf) = helper (acc + d) f
| (s /= Leaf) = helper (acc + d) s
treeHeight :: (Eq t1, Ord t, Num t) => Tree t1 -> t
treeHeight tree | tree == Leaf = 0
| otherwise = helper 0 tree where
helper acc (Node f _ s) | (f /= Leaf && s /= Leaf) =
let {fHeight = (helper (acc + 1) f); sHeight = (helper (acc + 1) s)}
in if fHeight >= sHeight then fHeight else sHeight
| f/=Leaf = helper (acc + 1) f
| s /= Leaf = helper (acc + 1) s
| otherwise = acc + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment