Skip to content

Instantly share code, notes, and snippets.

@mgechev
Last active December 19, 2015 05:59
Show Gist options
  • Select an option

  • Save mgechev/5908653 to your computer and use it in GitHub Desktop.

Select an option

Save mgechev/5908653 to your computer and use it in GitHub Desktop.
Finds the count of all interesting nodes in a binary tree (i.e. count of all nodes which has value equal to the count of their children)
data Tree = Nil | Node Int Tree Tree deriving (Eq)
interestingNodesCount Nil = 0
interestingNodesCount (Node a Nil Nil) = if a == 0 then 1 else 0
interestingNodesCount (Node a left right)
| left /= Nil && right == Nil && a == 1 = 1 + interestingNodesCount left
| left == Nil && right /= Nil && a == 1 = 1 + interestingNodesCount right
| left /= Nil && right == Nil && a /= 1 = 0 + interestingNodesCount left
| left == Nil && right /= Nil && a /= 1 = 0 + interestingNodesCount right
| otherwise = (if a == 2 then 1 else 0) + (interestingNodesCount left) + (interestingNodesCount right)
-- | left /= Nil && right /= Nil && a == 2 = 1 + (interestingNodesCount left) + (interestingNodesCount right)
-- | left /= Nil && right /= Nil && a /= 2 = 0 + (interestingNodesCount left) + (interestingNodesCount right)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment