Skip to content

Instantly share code, notes, and snippets.

@abhin4v
Created December 28, 2011 11:28
Show Gist options
  • Select an option

  • Save abhin4v/1527635 to your computer and use it in GitHub Desktop.

Select an option

Save abhin4v/1527635 to your computer and use it in GitHub Desktop.
Create a sumtree given the value of root node and depth of tree
data Tree a = NullNode | Node a (Tree a) (Tree a)
instance (Show a) => Show (Tree a) where
show NullNode = ""
show (Node x NullNode NullNode) = show x
show (Node x l r) = show x ++ "(" ++ show l ++ " " ++ show r ++ ")"
sumtree :: Int -> Int -> Tree Int
sumtree rootVal depth
| depth == 1 = Node rootVal NullNode NullNode
| otherwise = Node rootVal (sumtree leftSum (depth - 1)) (sumtree rightSum (depth - 1))
where leftSum = if even rootVal
then if depth == 2 then rootVal `div` 2 else rootVal `div` 4
else if depth == 2 then rootVal `div` 2 else (rootVal -1) `div` 4
rightSum = if even rootVal
then if depth == 2 then rootVal - leftSum else (rootVal `div` 2) - leftSum
else if depth == 2 then rootVal - leftSum else (rootVal `div` 2) - leftSum + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment