Exercise 7.2.2 Complete the following implementations of function contains and insert for IntTree’s.
This is similar to the IntSet implementations in Chapter 6.
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
object IntTreeTest { | |
abstract class IntTree | |
case object EmptyTree extends IntTree | |
case class Node(elem: Int, left: IntTree, right: IntTree) extends IntTree | |
def contains(t: IntTree, v: Int): Boolean = t match { | |
case EmptyTree => false | |
case Node(e, l, r) => | |
if (v < e) contains(l, v) | |
else if (v > e) contains(r, v) | |
else true | |
} | |
def insert(t: IntTree, v: Int): IntTree = t match { | |
case EmptyTree => Node(v, EmptyTree, EmptyTree) | |
case Node(e, l, r) => | |
if (v < e) Node(e, insert(l, v), r) | |
else if (v > e) Node(e, l, insert(r, v)) | |
else t | |
} | |
def main(args: Array[String]) { | |
val t = insert(insert(insert(insert(insert(EmptyTree, 11), 1), 20), 18), 25) | |
println("Tree is: " + t) | |
println("Does Tree contain 20?: " + (if (contains(t, 20)) "Yes" else "No")) | |
println("Does Tree contain 15?: " + (if (contains(t, 15)) "Yes" else "No")) | |
} | |
} |
No comments:
Post a Comment