added assignment 4 ex 2

This commit is contained in:
Louis Heredero 2025-03-11 15:49:58 +01:00
parent 1dc768ae51
commit 34f88cdf28
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7

@ -0,0 +1,22 @@
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)