22 lines
639 B
Scala

sealed abstract class BinaryTree
case class Leaf(value: Int) extends BinaryTree
case class Node(left: BinaryTree, right: BinaryTree) extends BinaryTree
def leafSum(tree: BinaryTree): Int = {
tree match {
case Leaf(value) => value
case Node(left, right) => leafSum(left) + leafSum(right)
}
}
def min(a: Int, b: Int): Int = if (a < b) a else b
def smallest(tree: BinaryTree): Int = {
tree match {
case Leaf(value) => value
case Node(left, right) => min(smallest(left), smallest(right))
}
}
assert(leafSum(Node(Node(Leaf(3), Leaf(8)), Leaf(5))) == 16)
assert(smallest(Node(Node(Leaf(3), Leaf(5)), Leaf(-5))) == -5)