hauzer

Haskell binary tree height example

Feb 3rd, 2013
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. data Tree a = Tree a (Maybe (Tree a)) (Maybe (Tree a))
  2.               deriving (Show)
  3.  
  4. treeHeight :: Maybe (Tree a) -> Int
  5. treeHeight Nothing                                      = 0
  6. treeHeight (Just (Tree _   Nothing       Nothing    ))  = 1
  7. treeHeight (Just (Tree _  (Just left)    Nothing    ))  = 1 + treeHeight (Just left)
  8. treeHeight (Just (Tree _   Nothing      (Just right)))  = 1 + treeHeight (Just right)
  9. treeHeight (Just (Tree _  (Just left)   (Just right)))
  10.          | leftHeight > rightHeight   = 1 + leftHeight
  11.          | leftHeight < rightHeight   = 1 + rightHeight
  12.          | otherwise                  = 1
  13.          where leftHeight     = treeHeight (Just left)
  14.                rightHeight    = treeHeight (Just right)
Advertisement
Add Comment
Please, Sign In to add comment