Skip to content

Commit

Permalink
Implement exercise 2.5.
Browse files Browse the repository at this point in the history
BinaryTree now knows how to create balanced versions of itself, with
inner structural sharing. Tests included, using ScalaCheck
  • Loading branch information
jordanlewis committed Dec 4, 2012
1 parent 82495cc commit 05335b5
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
2 changes: 2 additions & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@ version := "1.0"

scalaVersion := "2.9.1"

libraryDependencies += "org.scala-tools.testing" %% "scalacheck" % "1.9" % "test"

libraryDependencies += "org.scalatest" %% "scalatest" % "1.6.1" % "test"

21 changes: 21 additions & 0 deletions src/main/scala/BinaryTree.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
package org.jordanlewis.pfds

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)
}
}
}

sealed abstract class BinaryTree[+T] {
def size(): Int
}
Expand Down
23 changes: 23 additions & 0 deletions src/test/scala/BinaryTreeTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package org.jordanlewis.pfds

import org.scalatest.matchers.ShouldMatchers
import org.scalatest.Spec
import org.scalatest.prop.Checkers
import org.scalacheck.Prop._
import org.scalacheck.Gen._

class BinaryTreeTest extends Spec with ShouldMatchers with Checkers {
describe("A complete tree") {
it("should have 2^n - 1 nodes") {
check(forAll(choose(0, 25)){n: Int =>
BinaryTree.complete(0, n).size == scala.math.pow(2, n) - 1 })
}
}

describe("A balanced tree") {
it("should have n nodes") {
check(forAll(choose(0, 100)){n: Int =>
BinaryTree.balanced(0, n).size == n})
}
}
}

0 comments on commit 05335b5

Please sign in to comment.