BST Delete

Remove a key from a binary search tree, replacing a two-child node with its in-order successor.

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

How it works

Remove a key from a binary search tree, replacing a two-child node with its in-order successor.

Implementation

function bstDeleteOp(state, target) {
  const keys = state.keys;
  const left = state.left;
  const right = state.right;
  let parent = -1;
  let current = state.root;
  while (current !== -1 && keys[current] !== target) {
    visitNode(current);
    compareKeys(current, target);
    parent = current;
    if (target < keys[current]) {
      current = left[current];
    } else {
      current = right[current];
    }
  }
  if (current === -1) {
    reportNotFound();
    return;
  }
  reportFound(current);
  if (left[current] !== -1 && right[current] !== -1) {
    let succParent = current;
    let succ = right[current];
    while (left[succ] !== -1) {
      visitNode(succ);
      succParent = succ;
      succ = left[succ];
    }
    keys[current] = keys[succ];
    updateNode(current, keys[succ]);
    parent = succParent;
    current = succ;
  }
  let child = right[current];
  if (left[current] !== -1) {
    child = left[current];
  }
  if (parent === -1) {
    state.root = child;
  } else if (left[parent] === current) {
    left[parent] = child;
    if (child !== -1) {
      linkNodes(parent, child);
    }
  } else {
    right[parent] = child;
    if (child !== -1) {
      linkNodes(parent, child);
    }
  }
  removeNode(current);
  finish(current);
}