Previously, I posted an incorrect implementation of making a binary, balanced tree from a list of a
's.
Here's my second implementation:
data Tree a = Leaf
| Node Integer (Tree a) a (Tree a)
deriving (Show, Eq)-- where Integer is the height (bottom = 0)
-- make balanced, binary tree (height diff is 1 at most)
foldTree :: [a] -> Tree a
foldTree [] = Leaf
foldTree xxs@(x:xs) = Node level (foldTree first) x (foldTree rest)
where (first, rest) = splitInHalf xs
level = getBinTreeHt xxs
splitInHalf :: [a] -> ([a], [a])
splitInHalf xs = splitAt mid xs
where mid = length xs `div` 2
-- Get the total height of a tree given a list of [a] to create a Tree
getBinTreeHt :: [a] -> Integer
getBinTreeHt = floor . (logBase 2) . fromIntegral . length
Testing
Note that prettyTree
's implementation is excluded from this question since it's a library for visually representing a tree. Credit to this answer for prettyTree
.
*Main> (putStrLn . prettyTree . foldTree) [0..15]
15
14
12
13
8
11
9
10
0
7
5
6
1
4
2
3