Skip to content

Instantly share code, notes, and snippets.

@superfunc
Created October 8, 2014 20:11
Show Gist options
  • Save superfunc/a5c3ee6dd4565cfed52d to your computer and use it in GitHub Desktop.
Save superfunc/a5c3ee6dd4565cfed52d to your computer and use it in GitHub Desktop.
tree balance
{-# LANGUAGE GADTs, KindSignatures #-}
data Tree :: * where
Leaf :: Int -> Tree
Node :: Tree -> Tree -> Tree
deriving (Show,Eq,Ord)
-- Write a function that sums the leaf values in a tree
summation :: Tree -> Int
summation (Leaf v) = v
summation (Node l r) = (summation l) + (summation r)
-- Write a function that finds the depth of a tree
depth :: Tree -> Int
depth (Leaf _) = 0
depth (Node l r) = 1 + max (depth l) (depth r)
list :: Tree -> [Int]
list (Leaf v) = [v]
list (Node l r) = list l ++ list r
-- Write a function that balances a binary tree
balance :: Tree -> Tree
balance t = genBalancedTree $ map Leaf $ list t
where genBalancedTree [x] = x
genBalancedTree (x:y:zs) = genBalancedTree $ reverse $ Node x y : zs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment