---
# System prepended metadata

title: Lecture 23 Setup/Prep
tags: [Setup]

---

---
tags: Setup
---

# Lecture 23 Setup/Prep

Last class, we were introduced to *heaps*, a variant of binary trees in which the largest (alternatively, smallest) value in the tree is stored at the root, and every subtree is also a heap. Working with pictures of heaps, we illustrated how to insert and delete elements in a heap by swapping elements up and down the branches.

In this class, we will discuss how to implement this.

Based on the diagrams from last class, our implementation will need to be able to:

- track the next empty space at the bottom of the heap (for insert) or the last used space (for delete)
- get from a node to its parent (for insert) or child (for delete) within the underlying tree

## Prep

Here is a class-based implementation of binary trees (similar to what we did earlier this semester in Java) and a trait for Heaps. Think about what we would need to do to support the two needs we just identified with this tree class. What seems doable, what seems difficult?

```
trait IBinTree {} // an interface for tree nodes

// The tree classes showcase case classes in Scala.
// Case classes are useful for recursive data (see the 
//   BTExamples object): they can be created without using new
//   and come with .equals methods that compare all fields
case object EmptyBT extends IBinTree
case class NonEmptyBT(data: Int,
                      left: IBinTree,
                      right: IBinTree) extends IBinTree

object BTExamples {
  val bt1 = NonEmptyBT(
    5,
    NonEmptyBT(4, EmptyBT, EmptyBT),
    EmptyBT)
  val bt2 = NonEmptyBT(
    5,
    NonEmptyBT(4, EmptyBT, EmptyBT),
    EmptyBT)
}

// the heap interface
trait IHeap[T] {
  def getMax: Option[T]
  def insert(newElt: T): Unit
  def deleteMax(): Option[T]
}
```

