BST Search

Locate a key in a binary search tree by descending left or right based on comparisons.

Time O(h) Space O(1) Binary Search Tree search

How it works

Locate a key in a binary search tree by descending left or right based on comparisons.

Implementation

function bstSearchOp(state, target) {
  const keys = state.keys;
  const left = state.left;
  const right = state.right;
  let current = state.root;
  while (current !== -1) {
    visitNode(current);
    compareKeys(current, target);
    if (target === keys[current]) {
      reportFound(current);
      return;
    }
    if (target < keys[current]) {
      current = left[current];
    } else {
      current = right[current];
    }
  }
  reportNotFound();
}