AI 代码审查实战:JavaScript 持久化 AVL 有序集合、排名选择与历史版本验证
让 AI 写一棵二叉搜索树不难,让它同时满足平衡、排名、删除和历史版本隔离,才是真正的代码审查。一个漏掉的子树大小更新,可能让遍历结果完全正确,却把分页位置算错;一次看似普通的指针调整,也可能悄悄改写昨天保存的快照。本文围绕一个完整、范围明确的实现,把这些风险变成可执行的检查。
目标是只保存有限 Number 的持久化 AVL 有序集合。新增与删除返回新版本,旧版本仍可读取,也可以继续派生另一个分支。因此这里支持完全持久化。持久化指保留内存中的历史结构,不代表写入磁盘,也没有自动恢复、版本合并或并发事务功能。关于部分持久化与完全持久化的术语,可参阅原作者的Making Data Structures Persistent;本文采用直接路径复制,没有宣称复现论文中更复杂的常数摊还空间结果。
全部九个示例均为独立的 CommonJS 程序,复制任意一段保存为 example.cjs,即可用 node --unhandled-rejections=strict example.cjs 运行,不需要前文变量、第三方包或网络。已在 Node.js v24.19.0 实测。为保持独立性,后续示例会完整重复核心实现;输出单独列出,不属于可执行代码。严格拒绝未处理 Promise 的运行参数来自Node.js 命令行文档,但本文实现本身是同步算法。

一、先写数值与重复键契约,再请 AI 补代码
审查的第一步不是看旋转函数,而是问清楚什么可以成为键。本文接受有限的原始 Number,包括小数、极小值和极大值;拒绝 NaN、正负无穷、字符串、BigInt 和装箱数字。不隐式转换,可以避免查询时把用户输入的字符串当作现有数字。ECMAScript 对 Number.isFinite 的定义正好提供这种入口检查。
负零统一存成正零,二者算同一个键。重复插入不增加计数,并返回同一个版本对象;删除不存在的键也返回原对象。这里的大小表示不同键的数量,不是插入次数。排名表示严格小于查询键的键数,所以查询键不必存在。select 使用从零开始的位置,非法位置统一抛出 RangeError,空集合也不例外。
特别注意,有限 Number 不等于任意精度实数,也不等于安全整数。超出精确整数表示范围后,两个十进制字面量可能已经是同一个 Number;树无法恢复输入阶段丢失的信息。若业务使用巨大整数编号,应另定 BigInt 契约。示例还展示一个常见 AI 生成比较器:遇到 NaN 时,小于和大于都不成立,于是错误地宣布它与普通数字相等。
'use strict';
const assert = require('node:assert/strict');
function checkedKey(x) {
if (!Number.isFinite(x)) throw new TypeError('finite Number required');
return x === 0 ? 0 : x;
}
for (const x of [NaN, Infinity, -Infinity, '3', null, 3n, new Number(3)])
assert.throws(() => checkedKey(x), TypeError);
assert.equal(checkedKey(0.25), 0.25);
assert.equal(Object.is(checkedKey(-0), 0), true);
const badCompare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
assert.equal(badCompare(NaN, 7), 0);
assert.equal(9007199254740992, 9007199254740993);
console.log('finite keys; canonical zero; NaN comparator trap');运行输出:
finite keys; canonical zero; NaN comparator trap
二、旋转必须返回新节点,不能就地改旧指针
一个节点保存键、左右子树、高度与子树大小。空树高度和大小都为零,叶子高度为一。节点工厂根据已经完成的孩子重新计算两个缓存字段,再冻结对象。这样旋转无需手写增减公式,减少了旧高度和新大小混用的机会。每个新建节点都冻结,引用的孩子本身也来自同一个工厂,才构成整个可达结构的不可变性。
Object.freeze 的规范只处理当前对象,不会替我们递归冻结孩子。因此,简单冻结根对象并不能解决共享后代被修改的问题。示例选择只有原始数字和冻结节点的结构,并用严格模式写操作验证修改确实失败。返回给调用者的数组则是新的容器,修改它不会反向影响树。
右旋时提升左孩子,把原根及需要改变链接的节点重新构造,外围三棵子树直接沿用。代码中的相同引用断言验证了共享,值相等断言验证了旋转前后的内容。这里不是先深拷贝整棵树再改,而是仅复制必要节点。不要仅凭函数名里有 immutable 就认定安全,应逐条检查所有赋值的目标是否为旧节点。
'use strict';
const assert = require('node:assert/strict');
const h = n => n ? n.height : 0;
const s = n => n ? n.size : 0;
const node = (key, left = null, right = null) => Object.freeze({
key, left, right, height: 1 + Math.max(h(left), h(right)),
size: 1 + s(left) + s(right)
});
function rotateRight(n) {
const p = n.left;
return node(p.key, p.left, node(n.key, p.right, n.right));
}
function rotateLeft(n) {
const p = n.right;
return node(p.key, node(n.key, n.left, p.left), p.right);
}
const a = node(1), b = node(3), c = node(7);
const before = node(6, node(2, a, b), c);
const after = rotateRight(before);
assert.equal(after.key, 2);
assert.equal(after.left, a);
assert.equal(after.right.left, b);
assert.equal(after.right.right, c);
assert.equal(before.left.key, 2);
assert.notEqual(after.right, before);
assert.equal(after.height, 3);
assert.equal(after.size, 5);
assert.deepEqual(rotateLeft(after), before);
assert.throws(() => { before.key = 99; }, TypeError);
console.log('rotation: rebuilt 2 nodes; shared 3 subtrees');运行输出:
rotation: rebuilt 2 nodes; shared 3 subtrees
三、完整实现:沿搜索路径复制,回程时恢复平衡
下面是可以直接使用的完整工厂。公开方法通过闭包绑定各自版本的根,不依赖调用时的 this。root 只用于观察和测试,工厂不接受外部根节点,所以调用者无法把伪造的缓存字段注入正常版本。每次 add 或 delete 都先校验键,即使空树也不会跳过校验。若递归结果与原孩子引用相同,沿途直接返回原节点,最终保留版本对象身份。
平衡因子取左高度减右高度,超过一说明左侧过重,小于负一说明右侧过重。外侧较高时单旋,内侧较高时先旋孩子再旋当前根。本文的高度约定与部分教材的空树高度不同,但只要递推一致,差值和旋转选择不受影响。AVL 高度平衡与旋转的基础可核对 MIT 6.006 原始讲义。
删除两个孩子都存在的节点时,选择右子树最小键作为后继,并在新的右子树里删除这一个后继。旧节点从未修改。所有回程路径统一重新构造并平衡,避免为插入和删除维护两套容易分叉的缓存更新逻辑。示例先检查一个左右双旋以及两种无变化操作,后续再分别审查删除和排名的边界。
'use strict';
const assert = require('node:assert/strict');
function createAVL() {
const height = n => n ? n.height : 0;
const size = n => n ? n.size : 0;
function key(x) {
if (!Number.isFinite(x)) throw new TypeError('finite Number required');
return x === 0 ? 0 : x;
}
function node(key, left = null, right = null) {
return Object.freeze({ key, left, right,
height: 1 + Math.max(height(left), height(right)),
size: 1 + size(left) + size(right) });
}
function rotateRight(n) {
const p = n.left;
return node(p.key, p.left, node(n.key, p.right, n.right));
}
function rotateLeft(n) {
const p = n.right;
return node(p.key, node(n.key, n.left, p.left), p.right);
}
function balance(n) {
const d = height(n.left) - height(n.right);
if (d > 1) {
if (height(n.left.left) < height(n.left.right))
n = node(n.key, rotateLeft(n.left), n.right);
return rotateRight(n);
}
if (d < -1) {
if (height(n.right.right) < height(n.right.left))
n = node(n.key, n.left, rotateRight(n.right));
return rotateLeft(n);
}
return n;
}
function put(n, x) {
if (!n) return node(x);
if (x === n.key) return n;
if (x < n.key) {
const l = put(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
const r = put(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
function erase(n, x) {
if (!n) return null;
if (x < n.key) {
const l = erase(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
if (x > n.key) {
const r = erase(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
if (!n.left) return n.right;
if (!n.right) return n.left;
let successor = n.right;
while (successor.left) successor = successor.left;
return balance(node(successor.key, n.left,
erase(n.right, successor.key)));
}
function wrap(root) {
const api = Object.freeze({
root, size: size(root),
add(x) {
const r = put(root, key(x));
return r === root ? api : wrap(r);
},
delete(x) {
const r = erase(root, key(x));
return r === root ? api : wrap(r);
},
has(x) {
x = key(x);
let n = root;
while (n) {
if (x === n.key) return true;
n = x < n.key ? n.left : n.right;
}
return false;
},
rank(x) {
x = key(x);
let n = root, count = 0;
while (n) {
if (x <= n.key) n = n.left;
else { count += size(n.left) + 1; n = n.right; }
}
return count;
},
select(k) {
if (!Number.isSafeInteger(k) || k < 0 || k >= size(root))
throw new RangeError('rank out of range');
let n = root;
while (n) {
const left = size(n.left);
if (k === left) return n.key;
if (k < left) n = n.left;
else { k -= left + 1; n = n.right; }
}
throw new Error('invalid tree metadata');
},
values() {
const out = [];
function visit(n) {
if (!n) return;
visit(n.left); out.push(n.key); visit(n.right);
}
visit(root);
return out;
}
});
return api;
}
return wrap(null);
}
let v0 = createAVL();
let v1 = v0.add(30).add(10).add(20);
assert.deepEqual(v0.values(), []);
assert.deepEqual(v1.values(), [10, 20, 30]);
assert.equal(v1.root.key, 20);
assert.equal(v1.size, 3);
assert.equal(v1.add(20), v1);
assert.equal(v1.delete(99), v1);
assert.equal(v1.has(10), true);
assert.equal(v1.has(99), false);
console.log(JSON.stringify(v1.values()));运行输出:
[10,20,30]
四、四种旋转之外,还要证明共享没有污染历史
旋转测试应覆盖左左、右右、左右和右左四种插入路径。只插入升序数字通常只能验证其中一种,无法证明双旋正确。下面每一种都在插入最后一个键之前保存旧版本,之后同时检查新根、完整有序结果与旧结果;这样可以发现为了获得正确新树而破坏旧树的实现。
但内容没变还不足以说明路径复制有效。实现若每次都深拷贝,旧版本仍然正确,却失去了预期的更新空间优势。第二组断言选取不会触发顶层旋转的更新,检查整棵右子树和左侧未触碰分支仍然是相同引用。这个断言刻意针对可预测结构,并不要求每一种旋转之后,某个固定方向都保持同样的根引用。
也不要把引用身份当作所有语义比较的替代物。同一个版本的无操作应保留身份;两个通过不同插入顺序构造的集合,即使元素完全相同,也可以拥有不同形状和不同根。我们承诺给定操作历史的确定性,不承诺不同历史会自动合并成同一个对象。AI 审查意见应明确指出它检查的是哪一种相等性。
'use strict';
const assert = require('node:assert/strict');
function createAVL() {
const height = n => n ? n.height : 0;
const size = n => n ? n.size : 0;
function key(x) {
if (!Number.isFinite(x)) throw new TypeError('finite Number required');
return x === 0 ? 0 : x;
}
function node(key, left = null, right = null) {
return Object.freeze({ key, left, right,
height: 1 + Math.max(height(left), height(right)),
size: 1 + size(left) + size(right) });
}
function rotateRight(n) {
const p = n.left;
return node(p.key, p.left, node(n.key, p.right, n.right));
}
function rotateLeft(n) {
const p = n.right;
return node(p.key, node(n.key, n.left, p.left), p.right);
}
function balance(n) {
const d = height(n.left) - height(n.right);
if (d > 1) {
if (height(n.left.left) < height(n.left.right))
n = node(n.key, rotateLeft(n.left), n.right);
return rotateRight(n);
}
if (d < -1) {
if (height(n.right.right) < height(n.right.left))
n = node(n.key, n.left, rotateRight(n.right));
return rotateLeft(n);
}
return n;
}
function put(n, x) {
if (!n) return node(x);
if (x === n.key) return n;
if (x < n.key) {
const l = put(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
const r = put(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
function erase(n, x) {
if (!n) return null;
if (x < n.key) {
const l = erase(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
if (x > n.key) {
const r = erase(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
if (!n.left) return n.right;
if (!n.right) return n.left;
let successor = n.right;
while (successor.left) successor = successor.left;
return balance(node(successor.key, n.left,
erase(n.right, successor.key)));
}
function wrap(root) {
const api = Object.freeze({
root, size: size(root),
add(x) {
const r = put(root, key(x));
return r === root ? api : wrap(r);
},
delete(x) {
const r = erase(root, key(x));
return r === root ? api : wrap(r);
},
has(x) {
x = key(x);
let n = root;
while (n) {
if (x === n.key) return true;
n = x < n.key ? n.left : n.right;
}
return false;
},
rank(x) {
x = key(x);
let n = root, count = 0;
while (n) {
if (x <= n.key) n = n.left;
else { count += size(n.left) + 1; n = n.right; }
}
return count;
},
select(k) {
if (!Number.isSafeInteger(k) || k < 0 || k >= size(root))
throw new RangeError('rank out of range');
let n = root;
while (n) {
const left = size(n.left);
if (k === left) return n.key;
if (k < left) n = n.left;
else { k -= left + 1; n = n.right; }
}
throw new Error('invalid tree metadata');
},
values() {
const out = [];
function visit(n) {
if (!n) return;
visit(n.left); out.push(n.key); visit(n.right);
}
visit(root);
return out;
}
});
return api;
}
return wrap(null);
}
for (const order of [[30,20,10], [10,20,30], [30,10,20], [10,30,20]]) {
const old = createAVL().add(order[0]).add(order[1]);
const saved = old.values();
const next = old.add(order[2]);
assert.equal(next.root.key, 20);
assert.deepEqual(next.values(), [10,20,30]);
assert.deepEqual(old.values(), saved);
}
const base = [4,2,6,1,3,5,7].reduce((t,x) => t.add(x), createAVL());
const changed = base.add(0);
assert.notEqual(changed.root, base.root);
assert.equal(changed.root.right, base.root.right);
assert.equal(changed.root.left.right, base.root.left.right);
assert.deepEqual(base.values(), [1,2,3,4,5,6,7]);
assert.equal(base.add(3), base);
console.log('LL RR LR RL passed; untouched branches shared');运行输出:
LL RR LR RL passed; untouched branches shared
五、删除是独立风险:孩子平衡因子为零也要处理
删除往往比插入更容易留下缺口。移除一个节点后,较高孩子自身的左右高度可能恰好相同,这时仍应采用对应的单旋。若只根据最初被删除的键判断左右方向,或把双旋判断写成包含等号的条件,就可能选错旋转。本文直接读取当前孩子高度,严格比较内侧是否更高,将相等情况留给单旋。
四组固定案例分别覆盖左右镜像的零平衡孩子、删除双孩子根时选择后继,以及一直删到空树。每次删除后,检查器重新计算整棵树,而不是相信根上记录的高度。删除不存在的键单独验证身份,旧版本则与原始输入排序的结果核对。这样可以同时发现漏删后继、误删其他键、缓存未刷新和版本污染。
删除回程可能在多个祖先处恢复平衡,不能照搬插入时遇到一次修复就结束的推理。这里递归自然返回到根,每层都检查。即使某次平衡最终高度没变,已有实现也不会省略必要的大小重算。测试里的预期根只用于这些精心选择的固定案例,不把某个树形当成所有合法 AVL 实现唯一正确的答案。
'use strict';
const assert = require('node:assert/strict');
function createAVL() {
const height = n => n ? n.height : 0;
const size = n => n ? n.size : 0;
function key(x) {
if (!Number.isFinite(x)) throw new TypeError('finite Number required');
return x === 0 ? 0 : x;
}
function node(key, left = null, right = null) {
return Object.freeze({ key, left, right,
height: 1 + Math.max(height(left), height(right)),
size: 1 + size(left) + size(right) });
}
function rotateRight(n) {
const p = n.left;
return node(p.key, p.left, node(n.key, p.right, n.right));
}
function rotateLeft(n) {
const p = n.right;
return node(p.key, node(n.key, n.left, p.left), p.right);
}
function balance(n) {
const d = height(n.left) - height(n.right);
if (d > 1) {
if (height(n.left.left) < height(n.left.right))
n = node(n.key, rotateLeft(n.left), n.right);
return rotateRight(n);
}
if (d < -1) {
if (height(n.right.right) < height(n.right.left))
n = node(n.key, n.left, rotateRight(n.right));
return rotateLeft(n);
}
return n;
}
function put(n, x) {
if (!n) return node(x);
if (x === n.key) return n;
if (x < n.key) {
const l = put(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
const r = put(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
function erase(n, x) {
if (!n) return null;
if (x < n.key) {
const l = erase(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
if (x > n.key) {
const r = erase(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
if (!n.left) return n.right;
if (!n.right) return n.left;
let successor = n.right;
while (successor.left) successor = successor.left;
return balance(node(successor.key, n.left,
erase(n.right, successor.key)));
}
function wrap(root) {
const api = Object.freeze({
root, size: size(root),
add(x) {
const r = put(root, key(x));
return r === root ? api : wrap(r);
},
delete(x) {
const r = erase(root, key(x));
return r === root ? api : wrap(r);
},
has(x) {
x = key(x);
let n = root;
while (n) {
if (x === n.key) return true;
n = x < n.key ? n.left : n.right;
}
return false;
},
rank(x) {
x = key(x);
let n = root, count = 0;
while (n) {
if (x <= n.key) n = n.left;
else { count += size(n.left) + 1; n = n.right; }
}
return count;
},
select(k) {
if (!Number.isSafeInteger(k) || k < 0 || k >= size(root))
throw new RangeError('rank out of range');
let n = root;
while (n) {
const left = size(n.left);
if (k === left) return n.key;
if (k < left) n = n.left;
else { k -= left + 1; n = n.right; }
}
throw new Error('invalid tree metadata');
},
values() {
const out = [];
function visit(n) {
if (!n) return;
visit(n.left); out.push(n.key); visit(n.right);
}
visit(root);
return out;
}
});
return api;
}
return wrap(null);
}
function audit(root) {
const seen = new Set();
function walk(n, low, high) {
if (!n) return { height: 0, size: 0 };
assert(!seen.has(n), 'repeated node'); seen.add(n);
assert(Object.isFrozen(n), 'unfrozen node');
assert(Number.isFinite(n.key) && !Object.is(n.key, -0), 'key');
assert(low < n.key && n.key < high, 'order');
const l = walk(n.left, low, n.key);
const r = walk(n.right, n.key, high);
const height = 1 + Math.max(l.height, r.height);
const size = 1 + l.size + r.size;
assert.equal(n.height, height, 'height');
assert.equal(n.size, size, 'size');
assert(Math.abs(l.height - r.height) <= 1, 'balance');
return { height, size };
}
return walk(root, -Infinity, Infinity);
}
const fixtures = [
{ input:[4,2,5,1,3], remove:[5], root:2 },
{ input:[2,1,4,3,5], remove:[1], root:4 },
{ input:[4,2,6,1,3,5,7], remove:[4], root:5 },
{ input:[2,1,3], remove:[1,2,3], root:null }
];
for (const {input, remove, root} of fixtures) {
const old = input.reduce((t,x) => t.add(x), createAVL());
let next = old;
for (const x of remove) { next = next.delete(x); audit(next.root); }
assert.equal(next.root ? next.root.key : null, root);
assert.deepEqual(old.values(), [...input].sort((a,b) => a-b));
assert.deepEqual(next.values(), old.values().filter(x => !remove.includes(x)));
assert.equal(next.delete(100), next);
}
console.log('deletion: zero-balance child, successor, empty passed');运行输出:
deletion: zero-balance child, successor, empty passed
六、rank 与 select 的正确性来自跳过了多少键
rank 查询走向右侧时,整棵左子树以及当前键都严格小于查询值,故累加左子树大小再加一;查询值小于或等于当前键时则向左走,不把当前键计入。这个等号是最容易被 AI 在改写时弄错的地方。不存在的查询值也应该得到插入位置,不应返回负一或报不存在。
select 比较位置与左子树大小:相等就命中当前节点,更小就进入左侧,更大则跳过左侧和当前节点,减去左大小加一。它的输入是位置,不是键,所以单独使用安全整数与范围检查。负零位置等同于零;字符串位置、BigInt 位置、小数与越界值统一拒绝,不进行类型猜测。
下面的极端数值例子刻意包含 Number.MAX_VALUE 的两端和小数。实现使用直接大小比较,不依赖对键求差后再判断是否有限。对每个现有位置验证 rank(select(i)) 等于 i 很有价值,但它不是独立证明:两个函数可能犯互相抵消的错误。因此后面还会把二者分别与独立数组模型对照,并检查空树的失败行为。
'use strict';
const assert = require('node:assert/strict');
function createAVL() {
const height = n => n ? n.height : 0;
const size = n => n ? n.size : 0;
function key(x) {
if (!Number.isFinite(x)) throw new TypeError('finite Number required');
return x === 0 ? 0 : x;
}
function node(key, left = null, right = null) {
return Object.freeze({ key, left, right,
height: 1 + Math.max(height(left), height(right)),
size: 1 + size(left) + size(right) });
}
function rotateRight(n) {
const p = n.left;
return node(p.key, p.left, node(n.key, p.right, n.right));
}
function rotateLeft(n) {
const p = n.right;
return node(p.key, node(n.key, n.left, p.left), p.right);
}
function balance(n) {
const d = height(n.left) - height(n.right);
if (d > 1) {
if (height(n.left.left) < height(n.left.right))
n = node(n.key, rotateLeft(n.left), n.right);
return rotateRight(n);
}
if (d < -1) {
if (height(n.right.right) < height(n.right.left))
n = node(n.key, n.left, rotateRight(n.right));
return rotateLeft(n);
}
return n;
}
function put(n, x) {
if (!n) return node(x);
if (x === n.key) return n;
if (x < n.key) {
const l = put(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
const r = put(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
function erase(n, x) {
if (!n) return null;
if (x < n.key) {
const l = erase(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
if (x > n.key) {
const r = erase(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
if (!n.left) return n.right;
if (!n.right) return n.left;
let successor = n.right;
while (successor.left) successor = successor.left;
return balance(node(successor.key, n.left,
erase(n.right, successor.key)));
}
function wrap(root) {
const api = Object.freeze({
root, size: size(root),
add(x) {
const r = put(root, key(x));
return r === root ? api : wrap(r);
},
delete(x) {
const r = erase(root, key(x));
return r === root ? api : wrap(r);
},
has(x) {
x = key(x);
let n = root;
while (n) {
if (x === n.key) return true;
n = x < n.key ? n.left : n.right;
}
return false;
},
rank(x) {
x = key(x);
let n = root, count = 0;
while (n) {
if (x <= n.key) n = n.left;
else { count += size(n.left) + 1; n = n.right; }
}
return count;
},
select(k) {
if (!Number.isSafeInteger(k) || k < 0 || k >= size(root))
throw new RangeError('rank out of range');
let n = root;
while (n) {
const left = size(n.left);
if (k === left) return n.key;
if (k < left) n = n.left;
else { k -= left + 1; n = n.right; }
}
throw new Error('invalid tree metadata');
},
values() {
const out = [];
function visit(n) {
if (!n) return;
visit(n.left); out.push(n.key); visit(n.right);
}
visit(root);
return out;
}
});
return api;
}
return wrap(null);
}
const empty = createAVL();
const t = [-Number.MAX_VALUE, -0, 0.5, Number.MAX_VALUE]
.reduce((t,x) => t.add(x), empty);
assert.equal(t.size, 4);
assert.equal(t.add(0), t);
assert.equal(Object.is(t.select(1), 0), true);
for (const [x, rank] of [[-Number.MAX_VALUE,0], [-1,1], [-0,1], [0.5,2], [1,3]])
assert.equal(t.rank(x), rank);
for (let i=0; i<t.size; i++) assert.equal(t.rank(t.select(i)), i);
assert.equal(empty.rank(7), 0);
for (const k of [-1, 4, 0.2, NaN, Infinity, '0', 0n])
assert.throws(() => t.select(k), RangeError);
assert.throws(() => empty.select(0), RangeError);
for (const x of [NaN, Infinity, -Infinity, '0', null, 0n])
for (const method of ['add','delete','has','rank'])
assert.throws(() => empty[method](x), TypeError);
console.log('rank is strict-less; select is zero-based; zero normalized');运行输出:
rank is strict-less; select is zero-based; zero normalized
七、让不变量检查器拒绝自己制造的损坏
可靠的检查器必须从孩子重新计算高度与大小,并传递完整祖先界限。只检查左孩子小于当前键、右孩子大于当前键是不够的:更深的后代可能越过祖先边界。这里给每个节点传播严格上下界,同时验证数值、正零规范、冻结状态、平衡条件与节点身份唯一性。
单个版本必须是一棵树,不能让同一节点同时出现在两个位置,因此一次检查内使用独立的访问集合。不同版本之间共享节点完全合法,检查器不能把访问集合保留到下一次调用。检测重复引用也能阻止循环结构使递归无休止运行;这项防御主要用于检查器自身,并不是允许把任意外部图传入公开工厂。
示例把一个正常根改成错误大小、错误高度、错误键、失衡结构与重复孩子,确认每种损坏都被拒绝。所有这些都是另外创建的测试对象,没有修改真实版本。Node.js 的严格断言文档说明严格相等采用 Object.is 语义,因此测试正负零时必须先明确预期,不能依靠打印结果看起来都是零。
'use strict';
const assert = require('node:assert/strict');
function createAVL() {
const height = n => n ? n.height : 0;
const size = n => n ? n.size : 0;
function key(x) {
if (!Number.isFinite(x)) throw new TypeError('finite Number required');
return x === 0 ? 0 : x;
}
function node(key, left = null, right = null) {
return Object.freeze({ key, left, right,
height: 1 + Math.max(height(left), height(right)),
size: 1 + size(left) + size(right) });
}
function rotateRight(n) {
const p = n.left;
return node(p.key, p.left, node(n.key, p.right, n.right));
}
function rotateLeft(n) {
const p = n.right;
return node(p.key, node(n.key, n.left, p.left), p.right);
}
function balance(n) {
const d = height(n.left) - height(n.right);
if (d > 1) {
if (height(n.left.left) < height(n.left.right))
n = node(n.key, rotateLeft(n.left), n.right);
return rotateRight(n);
}
if (d < -1) {
if (height(n.right.right) < height(n.right.left))
n = node(n.key, n.left, rotateRight(n.right));
return rotateLeft(n);
}
return n;
}
function put(n, x) {
if (!n) return node(x);
if (x === n.key) return n;
if (x < n.key) {
const l = put(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
const r = put(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
function erase(n, x) {
if (!n) return null;
if (x < n.key) {
const l = erase(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
if (x > n.key) {
const r = erase(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
if (!n.left) return n.right;
if (!n.right) return n.left;
let successor = n.right;
while (successor.left) successor = successor.left;
return balance(node(successor.key, n.left,
erase(n.right, successor.key)));
}
function wrap(root) {
const api = Object.freeze({
root, size: size(root),
add(x) {
const r = put(root, key(x));
return r === root ? api : wrap(r);
},
delete(x) {
const r = erase(root, key(x));
return r === root ? api : wrap(r);
},
has(x) {
x = key(x);
let n = root;
while (n) {
if (x === n.key) return true;
n = x < n.key ? n.left : n.right;
}
return false;
},
rank(x) {
x = key(x);
let n = root, count = 0;
while (n) {
if (x <= n.key) n = n.left;
else { count += size(n.left) + 1; n = n.right; }
}
return count;
},
select(k) {
if (!Number.isSafeInteger(k) || k < 0 || k >= size(root))
throw new RangeError('rank out of range');
let n = root;
while (n) {
const left = size(n.left);
if (k === left) return n.key;
if (k < left) n = n.left;
else { k -= left + 1; n = n.right; }
}
throw new Error('invalid tree metadata');
},
values() {
const out = [];
function visit(n) {
if (!n) return;
visit(n.left); out.push(n.key); visit(n.right);
}
visit(root);
return out;
}
});
return api;
}
return wrap(null);
}
function audit(root) {
const seen = new Set();
function walk(n, low, high) {
if (!n) return { height: 0, size: 0 };
assert(!seen.has(n), 'repeated node'); seen.add(n);
assert(Object.isFrozen(n), 'unfrozen node');
assert(Number.isFinite(n.key) && !Object.is(n.key, -0), 'key');
assert(low < n.key && n.key < high, 'order');
const l = walk(n.left, low, n.key);
const r = walk(n.right, n.key, high);
const height = 1 + Math.max(l.height, r.height);
const size = 1 + l.size + r.size;
assert.equal(n.height, height, 'height');
assert.equal(n.size, size, 'size');
assert(Math.abs(l.height - r.height) <= 1, 'balance');
return { height, size };
}
return walk(root, -Infinity, Infinity);
}
const t = [8,4,12,2,6,10,14].reduce((t,x) => t.add(x), createAVL());
assert.deepEqual(audit(t.root), { height:3, size:7 });
const corrupt = patch => Object.freeze({ ...t.root, ...patch });
assert.throws(() => audit(corrupt({ size:8 })), /size/);
assert.throws(() => audit(corrupt({ height:4 })), /height/);
assert.throws(() => audit(corrupt({ key:1 })), /order/);
assert.throws(() => audit(corrupt({ right:null, size:4 })), /balance/);
assert.throws(() => audit(corrupt({ right:t.root.left })), /repeated node/);
const copy = t.values(); copy[0] = 999;
assert.deepEqual(t.values(), [2,4,6,8,10,12,14]);
assert.throws(() => { t.root.left.key = 100; }, TypeError);
console.log('audit rejects corrupt size, height, order, balance, alias');运行输出:
audit rejects corrupt size, height, order, balance, alias
八、独立排序数组预言机:穷举短历史,再抽查分支
数组模型完全不调用树的 rank、select、旋转或缓存计算。新增使用包含检查与重新排序,删除使用过滤;预期排名通过逐个计数小于查询值的元素得到,预期选择直接取数组下标。这个模型较慢,却足够简单,适合作为小数据的参考答案。预言机如果复用了被测算法的核心公式,就可能共享同一个错误。
穷举范围是三个键上的新增与删除,一共六种操作,向下展开六层,检查五万五千九百八十六条操作边。每条边都检查新版本,回程还重新检查父版本,覆盖同一个历史节点派生多个后续版本的情况。无变化操作则额外检查版本对象身份。这个有限穷举不等于覆盖所有输入,特别是三键集合无法代表复杂大树。
因此,再用固定种子的生成器在更宽的整数区间执行三千次更新,大部分延续最新版本,每五步有一次从历史中另开分支。完成后复查保存的所有版本,而不只看最新结果。没有等待、墙上时钟或外部网络,失败可以重现。固定种子本身不是随机测试充分性的证明,应把样本规模、操作分布和漏测边界一并交代。
'use strict';
const assert = require('node:assert/strict');
function createAVL() {
const height = n => n ? n.height : 0;
const size = n => n ? n.size : 0;
function key(x) {
if (!Number.isFinite(x)) throw new TypeError('finite Number required');
return x === 0 ? 0 : x;
}
function node(key, left = null, right = null) {
return Object.freeze({ key, left, right,
height: 1 + Math.max(height(left), height(right)),
size: 1 + size(left) + size(right) });
}
function rotateRight(n) {
const p = n.left;
return node(p.key, p.left, node(n.key, p.right, n.right));
}
function rotateLeft(n) {
const p = n.right;
return node(p.key, node(n.key, n.left, p.left), p.right);
}
function balance(n) {
const d = height(n.left) - height(n.right);
if (d > 1) {
if (height(n.left.left) < height(n.left.right))
n = node(n.key, rotateLeft(n.left), n.right);
return rotateRight(n);
}
if (d < -1) {
if (height(n.right.right) < height(n.right.left))
n = node(n.key, n.left, rotateRight(n.right));
return rotateLeft(n);
}
return n;
}
function put(n, x) {
if (!n) return node(x);
if (x === n.key) return n;
if (x < n.key) {
const l = put(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
const r = put(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
function erase(n, x) {
if (!n) return null;
if (x < n.key) {
const l = erase(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
if (x > n.key) {
const r = erase(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
if (!n.left) return n.right;
if (!n.right) return n.left;
let successor = n.right;
while (successor.left) successor = successor.left;
return balance(node(successor.key, n.left,
erase(n.right, successor.key)));
}
function wrap(root) {
const api = Object.freeze({
root, size: size(root),
add(x) {
const r = put(root, key(x));
return r === root ? api : wrap(r);
},
delete(x) {
const r = erase(root, key(x));
return r === root ? api : wrap(r);
},
has(x) {
x = key(x);
let n = root;
while (n) {
if (x === n.key) return true;
n = x < n.key ? n.left : n.right;
}
return false;
},
rank(x) {
x = key(x);
let n = root, count = 0;
while (n) {
if (x <= n.key) n = n.left;
else { count += size(n.left) + 1; n = n.right; }
}
return count;
},
select(k) {
if (!Number.isSafeInteger(k) || k < 0 || k >= size(root))
throw new RangeError('rank out of range');
let n = root;
while (n) {
const left = size(n.left);
if (k === left) return n.key;
if (k < left) n = n.left;
else { k -= left + 1; n = n.right; }
}
throw new Error('invalid tree metadata');
},
values() {
const out = [];
function visit(n) {
if (!n) return;
visit(n.left); out.push(n.key); visit(n.right);
}
visit(root);
return out;
}
});
return api;
}
return wrap(null);
}
function audit(root) {
const seen = new Set();
function walk(n, low, high) {
if (!n) return { height: 0, size: 0 };
assert(!seen.has(n), 'repeated node'); seen.add(n);
assert(Object.isFrozen(n), 'unfrozen node');
assert(Number.isFinite(n.key) && !Object.is(n.key, -0), 'key');
assert(low < n.key && n.key < high, 'order');
const l = walk(n.left, low, n.key);
const r = walk(n.right, n.key, high);
const height = 1 + Math.max(l.height, r.height);
const size = 1 + l.size + r.size;
assert.equal(n.height, height, 'height');
assert.equal(n.size, size, 'size');
assert(Math.abs(l.height - r.height) <= 1, 'balance');
return { height, size };
}
return walk(root, -Infinity, Infinity);
}
function oracle(a, op, x) {
x = x === 0 ? 0 : x;
if (op === 'delete') return a.filter(v => v !== x);
if (a.includes(x)) return a.slice();
return [...a,x].sort((p,q) => p < q ? -1 : p > q ? 1 : 0);
}
function check(t, expected) {
assert.deepEqual(t.values(), expected);
assert.equal(audit(t.root).size, expected.length);
for (let i=0; i<expected.length; i++) assert.equal(t.select(i), expected[i]);
for (const x of [-2,-1,-0,0.5,1,2]) {
assert.equal(t.rank(x), expected.filter(v => v < x).length);
assert.equal(t.has(x), expected.includes(x));
}
}
let edges = 0;
function explore(t, a, depth) {
check(t,a);
if (!depth) return;
for (const op of ['add','delete']) for (const x of [-1,0,1]) {
const b = oracle(a,op,x), next = t[op](x);
if (a.length === b.length) assert.equal(next,t);
edges++;
explore(next,b,depth-1);
check(t,a);
}
}
explore(createAVL(),[],6);
let seed=0x12345678;
function random() { seed=(Math.imul(seed,1664525)+1013904223)>>>0; return seed; }
const history=[{t:createAVL(),a:[]}];
for (let i=0; i<3000; i++) {
const old=i%5 === 0 ? history[(random()>>>8)%history.length] : history.at(-1);
const x=((random()>>>8)%201)-100;
const op=(random()>>>16)%2 ? 'add' : 'delete';
const next={t:old.t[op](x),a:oracle(old.a,op,x)};
check(next.t,next.a); check(old.t,old.a); history.push(next);
}
for (const v of history) check(v.t,v.a);
console.log(`exhaustive edges=${edges}; seeded branches=3000; all versions preserved`);运行输出:
exhaustive edges=55986; seeded branches=3000; all versions preserved
九、用变异测试反问 AI:这些测试真的能发现错误吗
测试全部通过还可能是测试太弱。最后一个示例先运行正常实现,再通过精确字符串替换创建五个故意损坏的实现:取消负零规范化、漏掉排名中的当前节点、错误调整选择位置、漏算子树根,以及复制后继键却不删除后继。每个替换目标都必须恰好出现一次,否则测试立即失败,避免代码改动后悄悄没有注入错误。
这里只在本地虚拟机上下文中执行文章自己构造的固定代码,不加载外部脚本,也不把 vm 当作不可信代码的安全沙箱。每个变体都由同一个探针触发失败,正常实现先通过,才能把失败解释为检验有效。杀死五个变体不是形式化证明,更不代表所有常见缺陷都已覆盖;它说明当前测试至少能对这五类明确错误发出信号。
把这个结果交给 AI 时,应要求它解释每个失败如何违反契约,而不是只让它把红灯改绿。若修复方案删除了历史版本断言、放宽了排名定义,或者绕过负零检查,表面通过也不算修好。审查的产物应是实现、明确边界、独立预期与可复现反例组成的证据,而不是一句笼统的代码看起来没问题。
'use strict';
const assert = require('node:assert/strict');
function createAVL() {
const height = n => n ? n.height : 0;
const size = n => n ? n.size : 0;
function key(x) {
if (!Number.isFinite(x)) throw new TypeError('finite Number required');
return x === 0 ? 0 : x;
}
function node(key, left = null, right = null) {
return Object.freeze({ key, left, right,
height: 1 + Math.max(height(left), height(right)),
size: 1 + size(left) + size(right) });
}
function rotateRight(n) {
const p = n.left;
return node(p.key, p.left, node(n.key, p.right, n.right));
}
function rotateLeft(n) {
const p = n.right;
return node(p.key, node(n.key, n.left, p.left), p.right);
}
function balance(n) {
const d = height(n.left) - height(n.right);
if (d > 1) {
if (height(n.left.left) < height(n.left.right))
n = node(n.key, rotateLeft(n.left), n.right);
return rotateRight(n);
}
if (d < -1) {
if (height(n.right.right) < height(n.right.left))
n = node(n.key, n.left, rotateRight(n.right));
return rotateLeft(n);
}
return n;
}
function put(n, x) {
if (!n) return node(x);
if (x === n.key) return n;
if (x < n.key) {
const l = put(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
const r = put(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
function erase(n, x) {
if (!n) return null;
if (x < n.key) {
const l = erase(n.left, x);
return l === n.left ? n : balance(node(n.key, l, n.right));
}
if (x > n.key) {
const r = erase(n.right, x);
return r === n.right ? n : balance(node(n.key, n.left, r));
}
if (!n.left) return n.right;
if (!n.right) return n.left;
let successor = n.right;
while (successor.left) successor = successor.left;
return balance(node(successor.key, n.left,
erase(n.right, successor.key)));
}
function wrap(root) {
const api = Object.freeze({
root, size: size(root),
add(x) {
const r = put(root, key(x));
return r === root ? api : wrap(r);
},
delete(x) {
const r = erase(root, key(x));
return r === root ? api : wrap(r);
},
has(x) {
x = key(x);
let n = root;
while (n) {
if (x === n.key) return true;
n = x < n.key ? n.left : n.right;
}
return false;
},
rank(x) {
x = key(x);
let n = root, count = 0;
while (n) {
if (x <= n.key) n = n.left;
else { count += size(n.left) + 1; n = n.right; }
}
return count;
},
select(k) {
if (!Number.isSafeInteger(k) || k < 0 || k >= size(root))
throw new RangeError('rank out of range');
let n = root;
while (n) {
const left = size(n.left);
if (k === left) return n.key;
if (k < left) n = n.left;
else { k -= left + 1; n = n.right; }
}
throw new Error('invalid tree metadata');
},
values() {
const out = [];
function visit(n) {
if (!n) return;
visit(n.left); out.push(n.key); visit(n.right);
}
visit(root);
return out;
}
});
return api;
}
return wrap(null);
}
function audit(root) {
const seen = new Set();
function walk(n, low, high) {
if (!n) return { height: 0, size: 0 };
assert(!seen.has(n), 'repeated node'); seen.add(n);
assert(Object.isFrozen(n), 'unfrozen node');
assert(Number.isFinite(n.key) && !Object.is(n.key, -0), 'key');
assert(low < n.key && n.key < high, 'order');
const l = walk(n.left, low, n.key);
const r = walk(n.right, n.key, high);
const height = 1 + Math.max(l.height, r.height);
const size = 1 + l.size + r.size;
assert.equal(n.height, height, 'height');
assert.equal(n.size, size, 'size');
assert(Math.abs(l.height - r.height) <= 1, 'balance');
return { height, size };
}
return walk(root, -Infinity, Infinity);
}
const vm = require('node:vm');
function probe(make) {
let t=make();
const versions=[];
for (const x of [4,2,6,1,3,5,7,-0]) {
versions.push({t,a:t.values()}); t=t.add(x); audit(t.root);
}
assert.equal(Object.is(t.select(0),0),true);
for (let i=0; i<t.size; i++) assert.equal(t.rank(t.select(i)),i);
assert.equal(t.add(3),t);
const old=t;
t=t.delete(4); audit(t.root);
assert.deepEqual(t.values(),[0,1,2,3,5,6,7]);
assert.deepEqual(old.values(),[0,1,2,3,4,5,6,7]);
for (const v of versions) assert.deepEqual(v.t.values(),v.a);
}
probe(createAVL);
const mutations=[
['zero', 'return x === 0 ? 0 : x;', 'return x;'],
['rank', 'count += size(n.left) + 1;', 'count += size(n.left);'],
['select', 'k -= left + 1;', 'k -= left;'],
['size', 'size: 1 + size(left) + size(right)', 'size: size(left) + size(right)'],
['successor', 'erase(n.right, successor.key)', 'n.right']
];
for (const [label,from,to] of mutations) {
const source=createAVL.toString();
assert.equal(source.split(from).length,2,'mutation target must be unique');
const mutant=vm.runInNewContext('('+source.replace(from,to)+')');
assert.throws(() => probe(mutant),undefined,label);
}
console.log('baseline passed; killed mutants=5');运行输出:
baseline passed; killed mutants=5
复杂度、边界与实际使用
对于当前版本中的 n 个不同键,AVL 高度为 O(log(n+1))。查找、排名、按位置选择以及单次增删都只沿有限条根到叶路径工作,时间为 O(log(n+1));实际改变集合的更新会分配 O(log(n+1)) 个节点,旋转每次只增加常数规模的构造。重复插入与无效删除虽然不创建新树节点,仍需搜索,所以不是常数时间。values 遍历与测试用 audit 都是 O(n),不能把它们放进每次更新后,再宣称整个业务流程只有对数时间。
保留大量历史根会保留仍被引用的节点;想释放历史,应释放应用自己保存的版本引用,不能修改共享子树。本文没有自动版本淘汰,也不支持按时间检索、合并两个分支、重复键计数、用户自定义比较器或跨进程序列化。计数字段采用 Number,面向能实际放入 JavaScript 堆内的集合,若要设计超大外存索引,需要重新审视计数和存储模型。
最后的审查清单可以压缩成四个问题:入口是否拒绝无序或含糊的值;每次更新是否只创建新节点;排名与选择是否分别对照独立预期;任何后续更新是否都不能改变历史答案。把这四点留在测试中,比让 AI 再生成一份更长、更漂亮的实现更有价值。

