From 34f88cdf282089461bde65d41d3743642cac2aa3 Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 11 Mar 2025 15:49:58 +0100 Subject: [PATCH] added assignment 4 ex 2 --- src/Assignment4/Ex2_Trees.sc | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/Assignment4/Ex2_Trees.sc diff --git a/src/Assignment4/Ex2_Trees.sc b/src/Assignment4/Ex2_Trees.sc new file mode 100644 index 0000000..b0e747f --- /dev/null +++ b/src/Assignment4/Ex2_Trees.sc @@ -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) \ No newline at end of file