Skip to content

Instantly share code, notes, and snippets.

@chadluo
Last active August 29, 2015 14:18
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 chadluo/a49425d83a5d88c9e696 to your computer and use it in GitHub Desktop.
Save chadluo/a49425d83a5d88c9e696 to your computer and use it in GitHub Desktop.
construct a balanced binary tree from a sorted array.
{-
construct a balanced binary tree from a _sorted_ array.
from haskell course exercise.
-}
data BinaryTree = Branch Integer BinaryTree BinaryTree
| Leaf
deriving (Show, Ord, Eq)
insert :: Integer -> BinaryTree -> BinaryTree
insert i Leaf = Branch i Leaf Leaf
insert i (Branch v l r)
| i < v = Branch v (insert i l) r
| otherwise = Branch v l (insert i r)
c :: [Integer] -> BinaryTree
c = foldl (flip insert) Leaf . b
b :: [Integer] -> [Integer]
b [] = []
b xs = let p = m xs in p : b (takeWhile (< p) xs) ++ b (dropWhile (<= p) xs)
m :: [Integer] -> Integer
m [x] = x
m [_,x] = x
m xs = m $ tail $ init xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment