Last active
August 29, 2015 14:18
-
-
Save chadluo/a49425d83a5d88c9e696 to your computer and use it in GitHub Desktop.
construct a balanced binary tree from a sorted array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{- | |
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