Created
January 9, 2016 15:20
-
-
Save semenodm/ffd4857b1487ac9281d7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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