BST Insert

Insert a key into a binary search tree, descending left for smaller keys and right for larger.

Time O(h) Space O(n) Binary Search Tree insert

How it works

Insert a key into a binary search tree, descending left for smaller keys and right for larger.

Implementation

function bstInsertOp(state, value) {
  const keys = state.keys;
  const left = state.left;
  const right = state.right;
  if (state.root === -1) {
    const id = keys.length;
    keys[id] = value;
    left[id] = -1;
    right[id] = -1;
    state.root = id;
    insertNode(id, value);
    finish(id);
    return;
  }
  let current = state.root;
  while (current !== -1) {
    compareKeys(current, value);
    if (value < keys[current]) {
      if (left[current] === -1) {
        const id = keys.length;
        keys[id] = value;
        left[id] = -1;
        right[id] = -1;
        left[current] = id;
        linkNodes(current, id);
        insertNode(id, value);
        finish(id);
        return;
      }
      current = left[current];
    } else {
      if (right[current] === -1) {
        const id = keys.length;
        keys[id] = value;
        left[id] = -1;
        right[id] = -1;
        right[current] = id;
        linkNodes(current, id);
        insertNode(id, value);
        finish(id);
        return;
      }
      current = right[current];
    }
  }
}