Skip to content

Instantly share code, notes, and snippets.

@schmmd
Created October 8, 2011 04:57
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save schmmd/1271891 to your computer and use it in GitHub Desktop.
Save schmmd/1271891 to your computer and use it in GitHub Desktop.
scala binary tree
/* contravariance required so Empty can be used with Nodes ( Nothing <: T ) */
class Tree[+T]
case object Empty extends Tree[Nothing]
case class Node[T](val elem: T, val left: Tree[T], val right: Tree[T]) extends Tree[T]
def inOrder[T](t: Tree[T]): List[T] = t match {
case Empty => Nil
case Node(e, left, right) => inOrder(left) ::: List(e) ::: inOrder(right)
}
def preOrder[T](t: Tree[T]): List[T] = t match {
case Empty => Nil
case Node(e, left, right) => e :: preOrder(left) ::: preOrder(right)
}
def postOrder[T](t: Tree[T]): List[T] = t match {
case Empty => Nil
case Node(e, left, right) => postOrder(left) ::: postOrder(right) ::: List(e)
}
def size[T](t: Tree[T]): Int = t match {
case Empty => 0
case Node(e, left, right) => 1 + size(left) + size(right)
}
def leafCount[T](t: Tree[T]): Int = t match {
case Empty => 0
case Node(e, Empty, Empty) => 1
case Node(e, left, right) => leafCount(left) + leafCount(right)
}
def leaves[T](t: Tree[T]): List[T] = t match {
case Empty => Nil
case Node(e, Empty, Empty) => List(e)
case Node(e, left, right) => leaves(left) ::: leaves(right)
}
def height[T](t: Tree[T]): Int = t match {
case Empty => 0
case Node(e, left, right) => 1 + math.max(height(left), height(right))
}
@oribus
Copy link

oribus commented Aug 30, 2014

That's very good, except a misleading error in the comment : "covariance is required", not "contravariance".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment