class WAVLTree extends AVLTree { isCorrectNode(node, recursive) { if (!node) { return true; } nodeDifferences(node).forEach((childRank) => { if ([1, 2].indexOf(childRank) == -1) { return false; } }); if (node.type() == LEAF) { return node.rank == 0; } return ( !(recursive ?? true) || (this.isCorrectNode(node.left) && this.isCorrectNode(node.right)) ); } fixDelete(x, y, z, reversed, rotatingAroundRoot, rotateLeft, rotateRight) { let newRoot = x; let [v, w] = [y.left, y.right]; if (reversed) { [v, w] = [w, v]; } let wDiff = nodeDifference(w, y); if (wDiff == 1 && y.parent) { newRoot = rotateLeft(y.parent); if (rotatingAroundRoot) { this.root = newRoot; } this.record(); y.promote(); this.record(); z.demote(); this.record(); if (z.type() == LEAF) { z.demote(); this.record(); } } else if (wDiff == 2 && v && v.parent) { rotateRight(v.parent); this.record(); newRoot = rotateLeft(v.parent); if (rotatingAroundRoot) { this.root = newRoot; } this.record(); v.promote().promote(); this.record(); y.demote(); this.record(); z.demote().demote(); this.record(); } } bottomUpDelete(x, parent) { let xDiff = nodeDifference(x, parent); if (xDiff != 3 || !parent) { return; } let y = parent.left === x ? parent.right : parent.left; let yDiff = nodeDifference(y, parent); while ( parent && xDiff == 3 && y && (yDiff == 2 || nodeDifferences(y).equals([2, 2])) ) { parent.demote(); this.record(); if (yDiff != 2) { y.demote(); this.record(); } x = parent; parent = x.parent; if (!parent) { return; } let y = parent.left === x ? parent.right : parent.left; xDiff = nodeDifference(x, parent); yDiff = nodeDifference(y, parent); } if (!parent) { return; } let rotatingAroundRoot = parent.parent == null; let parentNodeDiffs = nodeDifferences(parent); if (parentNodeDiffs.sort().equals([1, 3])) { if (parent.left === x) { this.fixDelete( x, parent.right, parent, false, rotatingAroundRoot, rotateLeft, rotateRight ); } else { this.fixDelete( x, parent.left, parent, true, rotatingAroundRoot, rotateRight, rotateLeft ); } } } deleteFixup(y, parent) { let z = y ? y : parent; if (nodeDifferences(z).equals([2, 2])) { z.demote(); this.record(); } if (!parent) { return; } [parent.left, parent.right].forEach((y) => { if (nodeDifference(y, parent) == 3) { this.bottomUpDelete(y, parent); } }); } deleteRebalance(node, parent) { while (node || parent) { this.deleteFixup(node, parent); ([node, parent] = parent), parent ? parent.parent : null; } } }