Skip to content

Instantly share code, notes, and snippets.

@mayonesa
Last active February 4, 2022 17:26
Show Gist options
  • Select an option

  • Save mayonesa/8fa0da578780f871bb47fe3e4e2c139c to your computer and use it in GitHub Desktop.

Select an option

Save mayonesa/8fa0da578780f871bb47fe3e4e2c139c to your computer and use it in GitHub Desktop.
package prep
class BST[E <: Ordered[E]](root: Node[E]) {
def this() = this(Empty())
lazy val seq = root.seq
def + (e: E): BST[E] = new BST(root + e)
def smallest(k: Int): E = seq(seq.size - k)
}
object BST {
def apply = new BST
}
trait Node[E <: Ordered[E]] {
def + (e: E): Node[E]
//def - (e: E): Node
def seq: IndexedSeq[E]
}
case class Empty[E <: Ordered[E]]() extends Node[E] {
def + (e: E): Node[E] = NonEmpty(Empty(), e, Empty())
def seq = IndexedSeq.empty[E]
}
case class NonEmpty[E <: Ordered[E]](l: Node[E], e: E, r: Node[E]) extends Node[E] {
def + (e: E): Node[E] =
if (e < this.e) NonEmpty(l + e, this.e, r)
else if (e > this.e) NonEmpty(l, this.e, r + e)
else this
def seq = (l.seq :+ e) ++ r.seq
}
@mayonesa

Copy link
Copy Markdown
Author

contains, -

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment