Created
May 6, 2014 00:53
-
-
Save kenbot/7c0683e347f0a871f559 to your computer and use it in GitHub Desktop.
Binary tree generation
This file contains 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
// Can it really be this hard??? | |
sealed trait BinTree | |
case class Node(left: BinTree, right: BinTree) extends BinTree | |
case class Leaf(n: Int) extends BinTree | |
def generateTree(ints: Iterable[Int]): BinTree = { | |
type BinTreePair = (BinTree, BinTree) | |
def pairOffTrees(trees: List[BinTree]): List[BinTreePair] = { | |
@tailrec | |
def pair(treesLeft: List[BinTree], | |
pairsSoFar: List[BinTreePair]): List[BinTreePair] = treesLeft match { | |
case a :: b :: rest => pair(rest, (a,b) :: pairsSoFar) | |
case _ => pairsSoFar | |
} | |
pair(trees, Nil) | |
} | |
def buildTrees(trees: List[BinTree]): List[BinTree] = { | |
@tailrec | |
def joinPairs(pairsLeft: List[BinTreePair], | |
treesSoFar: List[BinTree]): List[BinTree] = pairsLeft match { | |
case Nil => treesSoFar | |
case (a,b) :: rest => joinPairs(rest, Node(a,b) :: treesSoFar) | |
} | |
joinPairs(pairOffTrees(trees), Nil) | |
} | |
@tailrec | |
def reduceTrees(trees: List[BinTree]): BinTree = trees match { | |
case Nil => Leaf(0) | |
case t :: Nil => t | |
case _ => reduceTrees(buildTrees(trees)) | |
} | |
val leaves = ints.toList map Leaf.apply | |
reduceTrees(leaves) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment