- if (left[slot] == 0) {
- if (parent == 0) root = right[slot];
- else (left[parent] == slot ? left : right)[parent] = right[slot];
- right[slot] = 0;
- balance(slot, parent);
- } else if (right[slot] == 0) {
- if (parent == 0) root = left[slot];
- else (left[parent] == slot ? left : right)[parent] = left[slot];
- left[slot] = 0;
- balance(slot, parent);
+
+ // fast path: it has no left child, so we replace it with its right child
+ if (left[slot] < 0) {
+ (left[parent] == slot ? left : right)[parent] = right[slot]; // fix parent's pointer
+ if (right[slot] > 0) left[leftmost(right[slot])] = left[slot]; // fix our successor-leaf's fake left ptr
+ balance(right[slot], parent);
+
+ // fast path; it has no right child, so we replace it with its left child
+ } else if (right[slot] < 0) {
+ (left[parent] == slot ? left : right)[parent] = left[slot]; // fix parent's pointer
+ if (left[slot] > 0) right[rightmost(left[slot])] = right[slot]; // fix our successor-leaf's fake right ptr
+ balance(left[slot], parent);
+
+ // node to be deleted has two children, so we replace it with its left child's rightmost descendant