Кажется, что очевидная рекурсия работает нормально, по крайней мере, на ваших примерах:
case class Node[A](a: A, children: List[Node[A]])
def trieForest[A](lists: List[List[A]]): List[Node[A]] = {
lists.filter(_.nonEmpty).groupBy(_.head).map {
case (k, vs) =>
Node(k, trieForest(vs.map(_.tail)))
}.toList
}
def fromPaths(paths: List[String]): Node[String] = {
// assumes that there is only one tree in the
// top-level forest.
trieForest(paths.map(_.split("/").toList)).head
}
println(fromPaths(List("a/b/x", "a/b/y", "a/c", "a/c/d")))
Печать (с отступом):
Node(a, List(
Node(b,List(
Node(y,List()),
Node(x,List())
)),
Node(c,List(
Node(d,List())
))
))
Он не может работать намного быстрее асимптотически, потому что вы должны смотреть на каждую часть ввода хотя бы один раз.