Created
December 28, 2011 11:28
-
-
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
This file contains hidden or 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
| 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