Trees
BST Search
Search a binary search tree for one present and one absent value.
Algorithm
Basic Implementation
basic.scala
import scala.collection.mutable.{ArrayBuffer, Queue}
class Node(val value: Int, var left: Node = null, var right: Node = null)
object Main {
def render(node: Node): String = {
if (node == null) "_"
else if (node.left == null && node.right == null) node.value.toString
else s"${node.value}(${render(node.left)},${render(node.right)})"
}
def sampleTree(): Node = new Node(4, new Node(2, new Node(1), new Node(3)), new Node(6, new Node(5), new Node(7)))
def listString(values: Seq[Int]): String = values.mkString("[", ", ", "]")
def search(root: Node, target: Int): Boolean = { var node = root; while (node != null) { if (target == node.value) return true; node = if (target < node.value) node.left else node.right }; false }
def main(args: Array[String]): Unit = { val root = sampleTree(); println(if (search(root, 5)) "5 found" else "5 not found"); println(if (search(root, 8)) "8 found" else "8 not found") }
}
Complexity
- Time: O(h) per search
- Space: O(1) iterative
Implementation notes
class Node(val value: Int, var left: Node = null, var right: Node = null)gives each node an immutableIntvalue and mutable child references.- Empty links are plain
nullvalues in this source, notOption[Node]. search(root: Node, target: Int): Booleanis iterative:var node = rootis the moving cursor, and the loop stops when that cursor becomesnull.- Each loop checks
target == node.valuefirst and returnstrueimmediately on a match. - If the values differ,
target < node.valuemoves the cursor tonode.left; otherwise it moves tonode.right. Equal values are already handled by the match branch, so duplicates are not explored here. - The trace for
5shows the path4 -> right,6 -> left, then5 -> match. - The trace for missing
8walks4 -> right,6 -> right,7 -> right, then reachesnulland returnsfalse. mainprints the Boolean result as text, producing5 foundand8 not foundrather than rendering the searched nodes themselves.
search path
A comparison chooses one subtree at each step, so whole branches are skipped.