Skip to content

Instantly share code, notes, and snippets.

@yue82
Created May 23, 2017 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yue82/586e1818e126bdb192de8ba742550eaf to your computer and use it in GitHub Desktop.
Save yue82/586e1818e126bdb192de8ba742550eaf to your computer and use it in GitHub Desktop.
Scala training Binary Tree method
sealed abstract class Tree
case class Branch(value: Int, left: Tree, right: Tree) extends Tree
case object Empty extends Tree
object TreeObject {
def max(tree: Tree): Int = tree match {
case Branch(v, l, r) => math.max(math.max(v, this.max(l)), this.max(r))
case Empty => 0
}
def min(tree: Tree): Int = tree match {
case Branch(v, l, r) => math.min(math.min(v, this.min(l)), this.min(r))
case Empty => Int.MaxValue
}
def depth(tree: Tree): Int = tree match {
case Branch(v, l, r) => 1 + math.max(depth(l), depth(r))
case Empty => 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment