Created
December 4, 2012 23:15
-
-
Save jordanlewis/4210143 to your computer and use it in GitHub Desktop.
PFDS Exercise 2.5
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
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