added assignment 4 ex 2
This commit is contained in:
parent
1dc768ae51
commit
34f88cdf28
22
src/Assignment4/Ex2_Trees.sc
Normal file
22
src/Assignment4/Ex2_Trees.sc
Normal file
@ -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)
|
Loading…
x
Reference in New Issue
Block a user