web/wavl.js

166 lines
3.9 KiB
JavaScript
Raw Normal View History

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;
}
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) {
if (nodeDifferences(y).equals([2, 2])) {
y.demote();
this.record();
parent = y.parent;
} else if (nodeDifferences(parent).equals([2, 2])) {
parent.demote();
this.record();
parent = parent.parent;
}
if (!parent) {
return;
}
[parent.left, parent.right].forEach((y) => {
if (nodeDifference(y, parent) == 3) {
this.bottomUpDelete(y, parent);
}
});
}
deleteRebalance(node, parent) {
this.deleteFixup(node, parent);
}
}