LOGBOOK

HELP

Quiz Entry - updated: 2026.11.26

How does TreeSearch find a key in a binary search tree, and what does it return?

Starting at the root, it compares the key with the node's key: smaller goes left, larger goes right, equal returns that node. If it reaches an external node, the key is not in the tree and that external node is returned.

Algorithm TreeSearch(key, node)
  if node.isExternal()
    return node                           // not found: the gap where it would be
  if key < node.key()
    return TreeSearch(key, node.left())
  else if key = node.key()
    return node                           // found
  else                                    // key > node.key()
    return TreeSearch(key, node.right())

Every comparison discards one whole subtree, just as binary search discards half the array. The search walks a single path from the root downwards, so it costs time proportional to the depth it reaches, at most the height h of the tree.

Returning the external node on failure is deliberate: it is exactly the place where the key belongs. TreeSearch therefore always returns a node, never null. It is an internal helper; the public find(key) calls it with the root, checks isExternal() on the result and turns that into the caller-facing answer (the value, null, or an exception), while insert uses the same external node as the spot to place the new key.

Go deeper:

From Quiz: ADS / Binary Search Trees | Updated: Nov 26, 2026