Skip to content

Instantly share code, notes, and snippets.

@semenodm
Created January 9, 2016 15:20
Show Gist options
  • Select an option

  • Save semenodm/ffd4857b1487ac9281d7 to your computer and use it in GitHub Desktop.

Select an option

Save semenodm/ffd4857b1487ac9281d7 to your computer and use it in GitHub Desktop.
package org.sdo.alg.geeks
/**
* Created by dsemenov
* Date: 1/5/16.
*/
trait PossibleTrees[E] {
def findPossiblePreOrderTreesFor(inOrderTree: List[E]): List[List[E]] = inOrderTree match {
case Nil => Nil
case head :: Nil => List(List(head))
case l =>
(l.indices toList) flatMap { n =>
val nth = l(n)
val left = inOrderTree.take(n)
val right = inOrderTree.takeRight(l.length - n - 1)
val lef = findPossiblePreOrderTreesFor(left)
val rig = findPossiblePreOrderTreesFor(right)
if (lef.isEmpty) {
rig.map(nth :: _)
} else if (rig.isEmpty) {
lef.map(nth :: _)
} else {
for (
l <- lef;
r <- rig
) yield nth :: l ::: r
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment