Skip to content

Instantly share code, notes, and snippets.

@matthewleon
Created November 30, 2010 01:09
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 matthewleon/720950 to your computer and use it in GitHub Desktop.
Save matthewleon/720950 to your computer and use it in GitHub Desktop.
Convert a sorted list to a balanced binary search tree
{-# LANGUAGE PackageImports #-}
import "mtl" Control.Monad.State
data BinTree a = Tip | Node (BinTree a) a (BinTree a) deriving Show
conv :: Int -> State [a] (BinTree a)
conv 0 = return Tip
conv len = liftM3 Node leftTree pop rightTree
where leftTree = conv mid
rightTree = conv (len - mid - 1)
mid = len `div` 2
pop = get >>= \(l:ls) -> (put ls >> return l)
sortedListToBST :: [a] -> BinTree a
sortedListToBST ls = evalState (conv (length ls)) ls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment