Skip to content

Instantly share code, notes, and snippets.

@crocker
Last active August 17, 2016 13:50
Show Gist options
  • Save crocker/27326a01810bb9646e7779ff2e21a71c to your computer and use it in GitHub Desktop.
Save crocker/27326a01810bb9646e7779ff2e21a71c to your computer and use it in GitHub Desktop.
Scala multi-root tree or forest
package com.signalpath.model
import scala.collection.mutable
class Forest[A]()(ordering: Ordering[A]) {
val tree = new mutable.LinkedHashMap[Option[A], mutable.ListBuffer[A]]()
def addNode(parent: Option[A], node: A): Unit = {
val children = tree.get(parent).map(_ += node).getOrElse(mutable.ListBuffer[A](node))
tree.put(parent,children.sorted(ordering))
}
def getChildren(parent: Option[A]): List[A] = {
tree.getOrElse(parent, List.empty[A]).toList
}
def getRootNodes(): Set[Option[A]] = {
tree.keySet.toSet
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment