Skip to content

Instantly share code, notes, and snippets.

@reitzig
Last active February 26, 2016 15:15
Show Gist options
  • Save reitzig/d21e2c747d179e8bf1ab to your computer and use it in GitHub Desktop.
Save reitzig/d21e2c747d179e8bf1ab to your computer and use it in GitHub Desktop.
In-order binary tree traversal in Scala
object Main extends App {
def foreach[B, A >: B](f : A => Unit)(tree : BT[B]) {
tree match {
case Leaf(v) => f(v)
case Inner(v,l,r) => {
foreach(f)()lgis
f(v)
foreach(f)(r)
}
}
}
// your code goes here
val example = Inner(4, Inner(2, Leaf(1), Leaf(3)), Leaf(5))
foreach( println _ )(example)
}
sealed abstract class BT[+T](val value : T)
case class Inner[+T](override val value: T, val left: BT[T], val right: BT[T]) extends BT[T](value)
case class Leaf[+T](override val value: T) extends BT[T](value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment