Skip to content

Instantly share code, notes, and snippets.

@jordanlewis
Created December 4, 2012 23:15
Show Gist options
  • Save jordanlewis/4210143 to your computer and use it in GitHub Desktop.
Save jordanlewis/4210143 to your computer and use it in GitHub Desktop.
PFDS Exercise 2.5
object BinaryTree {
def complete[T](x: T, d: Int): BinaryTree[T] = d match {
case 0 => BinaryTreeLeaf
case _ => {
val subtree = complete(x, d - 1)
BinaryTreeNode(subtree, x, subtree)
}
}
def balanced[T](x: T, d: Int)(implicit ordering: Ordering[T]): BinaryTree[T] = d match {
case 0 => BinaryTreeLeaf
case 1 => BinaryTreeNode(BinaryTreeLeaf, x, BinaryTreeLeaf)
case _ => {
val half = d / 2
val halftree = create(x, half)
if (half * 2 == d) BinaryTreeNode(halftree, x, create(x, half - 1))
else BinaryTreeNode(halftree, x, halftree)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment