AI 写的伸展树能过审吗?用 JavaScript 审清旋转、访问调整与删除拼接
让 AI 写一棵有序映射,很容易得到一份“插入、查询、删除都齐了”的答案。伸展树尤其容易制造这种完成感:没有高度字段,没有颜色标记,几段旋转似乎就能结束工作。真正的审查却从这里开始。一次查询会改写哪些指针?找不到键时是否调整?删除根后,两棵子树凭什么能直接接起来?这些问题没有回答清楚,几组漂亮输出说明不了实现可靠。
本文把一份教学实现当作待审补丁,按契约、局部变换、整体不变量和独立对照四层检查。重点是伸展树的访问驱动调整,不再铺开平衡因子维护。九段示例均可分别保存为 .cjs 文件直接运行,使用 Node.js 内置严格断言,不安装第三方包。为了让示例真正独立,完整类在差分与接口测试中会再次出现;复制任何一段都不需要先执行前文。

一、先把“有序映射”缩成可以核验的契约
本实现只接受有限的 JavaScript Number 键,按数值升序排列;负零统一成正零,值可以是任意 JavaScript 值。NaN、无穷大、字符串、BigInt 和对象键都拒绝。限制键域不是算法要求,而是本文主动选择的接口边界。否则一个貌似简洁的比较器就会让审查范围扩展到混合类型、对象可变性、比较器传递性以及回调重入。
拒绝 NaN 特别重要。如果代码把“既不小于也不大于”当成相等,NaN 会和许多不同键碰撞。所有公开查找与修改入口必须先校验,再触碰结构。有限小数可以使用;超过安全整数范围的数仍按 JavaScript 已表示出来的数值处理,本实现不承诺恢复输入时已经丢失的整数精度。
原生 Map 在这里只负责键值关系,顺序要另行排序。它本身的遍历顺序不是本文要提供的数值顺序,不能把 Map 的 entries 直接当成有序结果。Map 对正负零的处理、键的相等语义,以及 get 返回 undefined 与 has 的区别,可在 ECMAScript 的 Map 规范中核对。这里把允许键限制为有限数值,正好让原生 Map 可以成为一个语义相符的独立对照。
示例一先固定这些边界。注意:存有 undefined 和根本没有这个键,是两个不同状态,不能用 get 的返回值代替 has。
"use strict";
const assert = require("node:assert/strict");
function keyOf(key) {
if (typeof key !== "number" || !Number.isFinite(key)) {
throw new TypeError("key must be a finite number");
}
return key === 0 ? 0 : key;
}
const m = new Map();
m.set(-0, undefined);
assert.equal(m.has(0), true);
assert.equal(m.get(0), undefined);
assert.equal(m.get(99), undefined);
assert.equal(Object.is(keyOf(-0), -0), false);
for (const bad of [NaN, Infinity, -Infinity, "1", 1n, null]) {
assert.throws(() => keyOf(bad), TypeError);
}
console.log("finite keys; -0 normalized; undefined is a valid value");运行输出:
finite keys; -0 normalized; undefined is a valid value
二、旋转审查的对象是整条连接关系
为了避免“向左转”的命名歧义,下面的 rotate(tree, x) 表示把子节点 x 提升到它的父节点位置。调用者保证 x 有父节点,树在调用前有效。若 x 原来是左孩子,x 的右子树会转交给旧父节点;另一方向完全对称。函数是内部原语,不负责把任意损坏的图修成合法树。
审查时不要只盯着提升后的两个节点。至少有四处关系要核对:中间子树的新父指针,旧父节点的新父指针,提升节点与祖父的连接,以及没有祖父时容器持有的根引用。漏掉第一处,向下遍历可能仍然有序,下一次向上伸展才暴露问题;漏掉最后一处,操作可能悄悄留下一个过期入口。
示例二故意在旋转区域之外保留祖父,并在两个关键节点之间放入非空中间子树。第一次旋转和反向旋转都核验对象身份,测试的是同一批节点有没有被正确重接,不只是节点的键最后看起来有没有排序。
"use strict";
const assert = require("node:assert/strict");
function node(key) {
return { key, left: null, right: null, parent: null };
}
function link(parent, side, child) {
parent[side] = child;
if (child) child.parent = parent;
}
function rotate(tree, x) {
const p = x.parent;
const g = p.parent;
if (p.left === x) {
p.left = x.right;
if (x.right) x.right.parent = p;
x.right = p;
} else {
p.right = x.left;
if (x.left) x.left.parent = p;
x.left = p;
}
p.parent = x;
x.parent = g;
if (!g) tree.root = x;
else if (g.left === p) g.left = x;
else g.right = x;
}
const g = node(50), p = node(20), x = node(10), middle = node(15);
link(g, "left", p); link(p, "left", x); link(x, "right", middle);
const tree = { root: g };
rotate(tree, x);
assert.equal(g.left, x); assert.equal(x.parent, g);
assert.equal(x.right, p); assert.equal(p.parent, x);
assert.equal(p.left, middle); assert.equal(middle.parent, p);
rotate(tree, p);
assert.equal(g.left, p); assert.equal(p.left, x);
assert.equal(x.right, middle); assert.equal(middle.parent, x);
console.log("both directions preserve middle subtree and grandparent links");运行输出:
both directions preserve middle subtree and grandparent links
三、把节点转到根,为什么还要区分两种双旋
伸展步骤分三种。父节点就是根时,做一次 zig;节点与父节点位于同一方向时,先提升父节点,再提升目标节点,称为 zig-zig;两者方向不同时,连续提升目标节点两次,称为 zig-zag。左右镜像都必须覆盖。“循环旋转目标直到成为根”只实现了移动到根的直觉,并不自动等价于这里的标准伸展规则。
这个区别不影响某一次操作结束后的中序排序,却影响后续路径形态。因此,把测试目标仅定为“根正确、键没丢”,仍可能放过错误的调整策略。审查双旋分支时,应明确第二次旋转读取的是已经更新过的父指针,不能继续按旧祖父位置写连接。
示例三单独覆盖左左、右右、左右和右左四种三节点形状。代码比较两个布尔表达式来判断方向是否相同,没有混入键比较;旋转策略依赖的是父子关系。这里的短测试是分支检查,不是性能定理的证明。
"use strict";
const assert = require("node:assert/strict");
function node(key) {
return { key, left: null, right: null, parent: null };
}
function link(parent, side, child) {
parent[side] = child;
if (child) child.parent = parent;
}
function rotate(tree, x) {
const p = x.parent;
const g = p.parent;
if (p.left === x) {
p.left = x.right;
if (x.right) x.right.parent = p;
x.right = p;
} else {
p.right = x.left;
if (x.left) x.left.parent = p;
x.left = p;
}
p.parent = x;
x.parent = g;
if (!g) tree.root = x;
else if (g.left === p) g.left = x;
else g.right = x;
}
function splay(tree, x) {
while (x.parent) {
const p = x.parent;
const g = p.parent;
if (!g) rotate(tree, x);
else if ((g.left === p) === (p.left === x)) {
rotate(tree, p);
rotate(tree, x);
} else {
rotate(tree, x);
rotate(tree, x);
}
}
}
for (const [a, b, c] of [[3, 2, 1], [1, 2, 3], [3, 1, 2], [1, 3, 2]]) {
const g = node(a), p = node(b), x = node(c);
link(g, b < a ? "left" : "right", p);
link(p, c < b ? "left" : "right", x);
const tree = { root: g };
splay(tree, x);
assert.equal(tree.root, x); assert.equal(x.parent, null);
const keys = [], stack = []; let cur = tree.root;
while (cur || stack.length) {
while (cur) { stack.push(cur); cur = cur.left; }
cur = stack.pop(); keys.push(cur.key); cur = cur.right;
}
assert.deepEqual(keys, [1, 2, 3]);
}
console.log("zig-zig and zig-zag, including mirrors: OK");运行输出:
zig-zig and zig-zag, including mirrors: OK
四、完整实现:查询失败,也要调整最后到达的节点
现在把局部操作装进完整映射。成功查找把命中节点伸展到根;查找失败则把沿搜索路径最后遇到的非空节点伸展到根;空树不做旋转。get 和 has 都采用这条规则,失败的 delete 也会改变树形。因此,“没有新增或删除键”不等于“没有写操作”。
set 先按普通二叉搜索树规则找位置。键已经存在时只替换值并伸展,size 不增加;新键则接到空位,size 增加一次,随后伸展新节点。这里的 size 是容器总节点数,不是每个节点的子树大小。我们没有实现按排名查询,也就不引入额外聚合字段的旋转维护责任。
lowerBound 返回第一个大于等于目标的键值对,没有候选时返回 null。向左下降前记录当前候选,向右下降时保留旧候选。本实现最后伸展的是搜索路径末端节点,而不承诺把返回候选变成根。这个选择让调整对象与实际走过的完整路径一致;返回对象和调整对象是两个变量,审查时不要把它们混成一个。
entries 返回一个升序数组快照,内部用显式栈中序遍历。伸展树的高度可能是线性的,递归版遍历和递归版完整校验可能先耗尽运行时调用栈。示例四把查找、插入、伸展和遍历都写成循环,同时保留完整导出,方便另存为模块后开展附加测试。
"use strict";
const assert = require("node:assert/strict");
function keyOf(key) {
if (typeof key !== "number" || !Number.isFinite(key)) {
throw new TypeError("key must be a finite number");
}
return key === 0 ? 0 : key;
}
function rotate(tree, x) {
const p = x.parent;
const g = p.parent;
if (p.left === x) {
p.left = x.right;
if (x.right) x.right.parent = p;
x.right = p;
} else {
p.right = x.left;
if (x.left) x.left.parent = p;
x.left = p;
}
p.parent = x;
x.parent = g;
if (!g) tree.root = x;
else if (g.left === p) g.left = x;
else g.right = x;
}
function splay(tree, x) {
while (x.parent) {
const p = x.parent;
const g = p.parent;
if (!g) rotate(tree, x);
else if ((g.left === p) === (p.left === x)) {
rotate(tree, p);
rotate(tree, x);
} else {
rotate(tree, x);
rotate(tree, x);
}
}
}
class SplayMap {
constructor() { this.root = null; this.size = 0; }
_find(key) {
let x = this.root, last = null;
while (x) {
last = x;
if (key === x.key) break;
x = key < x.key ? x.left : x.right;
}
if (last) splay(this, last);
return x;
}
get(key) { return this._find(keyOf(key))?.value; }
has(key) { return this._find(keyOf(key)) !== null; }
set(key, value) {
key = keyOf(key);
let x = this.root, parent = null;
while (x) {
parent = x;
if (key === x.key) {
x.value = value;
splay(this, x);
return this;
}
x = key < x.key ? x.left : x.right;
}
x = { key, value, left: null, right: null, parent };
if (!parent) this.root = x;
else if (key < parent.key) parent.left = x;
else parent.right = x;
this.size++;
splay(this, x);
return this;
}
delete(key) {
const x = this._find(keyOf(key));
if (!x) return false;
const left = x.left, right = x.right;
if (left) left.parent = null;
if (right) right.parent = null;
x.left = x.right = x.parent = null;
this.size--;
if (!left) this.root = right;
else {
this.root = left;
let max = left;
while (max.right) max = max.right;
splay(this, max);
this.root.right = right;
if (right) right.parent = this.root;
}
return true;
}
lowerBound(key) {
key = keyOf(key);
let x = this.root, last = null, best = null;
while (x) {
last = x;
if (x.key >= key) { best = x; x = x.left; }
else x = x.right;
}
if (last) splay(this, last);
return best ? [best.key, best.value] : null;
}
entries() {
const out = [], stack = [];
let x = this.root;
while (x || stack.length) {
while (x) { stack.push(x); x = x.left; }
x = stack.pop();
out.push([x.key, x.value]);
x = x.right;
}
return out;
}
}
if (require.main === module) {
const m = new SplayMap();
m.set(30, "C").set(10, "A").set(20, "B");
assert.equal(m.get(10), "A");
assert.equal(m.root.key, 10);
assert.deepEqual(m.lowerBound(15), [20, "B"]);
assert.equal(m.delete(20), true);
console.log(JSON.stringify(m.entries()));
}
module.exports = { SplayMap, keyOf };运行输出:
[[10,"A"],[30,"C"]]
五、删除的难点是 join 的前提,不是少一个节点
删除命中后,目标已经成为根。记它的左子树为 L,右子树为 R。合法二叉搜索树保证 L 的每个键都小于被删键,而 R 的每个键都大于被删键,因此 L 的所有键严格小于 R 的所有键。这个跨树顺序前提,是可以拼接的真正理由。
断开旧根时,应先把两边子树的 parent 置空,再清除旧根的连接。否则在 L 内进行伸展时,向上路径可能穿过已删除的根,把本应离开的节点带回来。只有 L 为空时才直接采用 R;R 为空时也可以走一般流程,得到合法结果。
L 非空时,把 L 的最大节点伸展到 L 的根。最大节点没有右孩子,所以它的右侧恰好能完整接入 R,不会覆盖尚未搬走的分支。随后还要设置 R 的反向父指针。这个步骤可以用“小于分界的集合”和“大于分界的集合”解释,远比凭树图猜哪个节点合适更稳。
示例五抽出最小 join。它仅供内部调用,前提是两棵输入树各自有效、节点互不共享、左侧所有键都严格小于右侧所有键。它会消费并改变输入树,不是返回共享旧结构的持久化操作。若要把 join 开放成公共 API,必须另外规定前提由谁验证,以及失败时是否保持原状。不要给任意两棵树调用它,再把有序性破坏归咎于旋转。
"use strict";
const assert = require("node:assert/strict");
function node(key) {
return { key, left: null, right: null, parent: null };
}
function link(parent, side, child) {
parent[side] = child;
if (child) child.parent = parent;
}
function rotate(tree, x) {
const p = x.parent;
const g = p.parent;
if (p.left === x) {
p.left = x.right;
if (x.right) x.right.parent = p;
x.right = p;
} else {
p.right = x.left;
if (x.left) x.left.parent = p;
x.left = p;
}
p.parent = x;
x.parent = g;
if (!g) tree.root = x;
else if (g.left === p) g.left = x;
else g.right = x;
}
function splay(tree, x) {
while (x.parent) {
const p = x.parent;
const g = p.parent;
if (!g) rotate(tree, x);
else if ((g.left === p) === (p.left === x)) {
rotate(tree, p);
rotate(tree, x);
} else {
rotate(tree, x);
rotate(tree, x);
}
}
}
function join(left, right) {
if (!left) { if (right) right.parent = null; return right; }
left.parent = null;
if (right) right.parent = null;
const tree = { root: left };
let max = left;
while (max.right) max = max.right;
splay(tree, max);
assert.equal(tree.root.right, null);
tree.root.right = right;
if (right) right.parent = tree.root;
return tree.root;
}
const left = node(2), max = node(4), middle = node(3), right = node(9);
link(left, "right", max); link(max, "left", middle);
const root = join(left, right);
assert.equal(root, max); assert.equal(root.parent, null);
assert.equal(root.left, left); assert.equal(left.right, middle);
assert.equal(middle.parent, left); assert.equal(root.right, right);
assert.equal(right.parent, root);
assert.equal(join(null, null), null);
console.log("join root=4; 2 < 3 < 4 < 9; empty join OK");运行输出:
join root=4; 2 < 3 < 4 < 9; empty join OK
六、中序有序只是一个信号,不能代替结构校验
接下来建立与操作实现分离的校验器。每个节点必须满足祖先传下来的开区间,而不仅是“比直接左孩子大,比直接右孩子小”。根为十、左孩子为五、五的右孩子为十二,就是局部父子比较容易漏掉的反例:十二虽然大于五,却已经越过祖先十的边界。
校验器还检查每个可达节点的 parent 正好指回进入它的父节点,根的 parent 必须为 null;同一个对象不能第二次出现,这同时排除环与多父共享;最终可达对象数必须等于 size。四层检查组合起来,才能抓住“查询还返回正确值,但结构已经坏了”的中间状态。
这里对每个操作都做完整校验,只用于测试。它需要与节点数成正比的时间和辅助空间,不能悄悄放进生产热路径后,继续把整个 API 描述成对数摊还成本。辅助工具自己的成本也属于审查范围。
示例六先构造违反祖先范围的树,再依次制造错误父指针、环和错误 size。测试应当证明校验器能拒绝已知坏结构,不能只让它在正确树上重复报喜。校验器不是内存隔离机制;示例把节点字段公开用于教学,生产封装仍应阻止调用者直接改写 root、size 或节点链接。
"use strict";
const assert = require("node:assert/strict");
function node(key) {
return { key, left: null, right: null, parent: null };
}
function link(parent, side, child) {
parent[side] = child;
if (child) child.parent = parent;
}
function validate(tree) {
const seen = new Set();
const stack = tree.root ? [[tree.root, null, -Infinity, Infinity]] : [];
while (stack.length) {
const [x, parent, low, high] = stack.pop();
assert(!seen.has(x), "cycle or shared child");
seen.add(x);
assert.equal(x.parent, parent, "parent link");
assert(Number.isFinite(x.key) && low < x.key && x.key < high,
"strict ancestor bounds");
if (x.left) stack.push([x.left, x, low, x.key]);
if (x.right) stack.push([x.right, x, x.key, high]);
}
assert.equal(seen.size, tree.size, "reachable size");
}
const root = node(10), left = node(5), escaped = node(12);
link(root, "left", left); link(left, "right", escaped);
assert.throws(() => validate({ root, size: 3 }), /ancestor bounds/);
escaped.key = 7;
validate({ root, size: 3 });
escaped.parent = root;
assert.throws(() => validate({ root, size: 3 }), /parent link/);
escaped.parent = left;
escaped.left = root;
assert.throws(() => validate({ root, size: 3 }), /cycle or shared child/);
escaped.left = null;
assert.throws(() => validate({ root, size: 4 }), /reachable size/);
console.log("ancestor bounds, parent links, cycles and size: checked");运行输出:
ancestor bounds, parent links, cycles and size: checked
七、差分 oracle 必须走另一条实现路线
如果拿第二棵几乎一样的伸展树对照第一棵,两个实现可能共享同一个旋转错误。这里的 oracle 只用原生 Map 保存键值,用排序数组回答升序枚举与 lowerBound;它没有 parent、rotate 或 join,所以不会因为复用了树的控制流而一起犯错。
示例七穷尽三个键、五种操作、长度一到四的全部非空历史,一共五万四千二百四十条。每条历史都从空状态重建,每一个操作后检查结构、size 和完整键值序列;返回值也与 oracle 比较。零键保存 undefined,因此 has 与 get 的区别会自然进入混合操作历史。
这组穷尽测试的边界必须原样写清。它并没有穷尽所有 JavaScript 数值、任意长历史或全部对象值;也没有证明摊还复杂度。它提供的是一个可复现的有限域证据,比“随机跑了一会儿没报错”具体得多。把失败历史直接打印或保存下来,通常就能把 AI 生成代码里的长链问题压缩成可解释的短反例。
下方重复完整实现是为了让这一段能独立运行。实际仓库应从同一实现文件导入,避免产品代码修好了、测试副本仍停在旧版本。正式审查还应要求确定性随机种子、失败时的操作序列、运行时版本,以及对新增反例的固定回归测试。
"use strict";
const assert = require("node:assert/strict");
function keyOf(key) {
if (typeof key !== "number" || !Number.isFinite(key)) {
throw new TypeError("key must be a finite number");
}
return key === 0 ? 0 : key;
}
function rotate(tree, x) {
const p = x.parent;
const g = p.parent;
if (p.left === x) {
p.left = x.right;
if (x.right) x.right.parent = p;
x.right = p;
} else {
p.right = x.left;
if (x.left) x.left.parent = p;
x.left = p;
}
p.parent = x;
x.parent = g;
if (!g) tree.root = x;
else if (g.left === p) g.left = x;
else g.right = x;
}
function splay(tree, x) {
while (x.parent) {
const p = x.parent;
const g = p.parent;
if (!g) rotate(tree, x);
else if ((g.left === p) === (p.left === x)) {
rotate(tree, p);
rotate(tree, x);
} else {
rotate(tree, x);
rotate(tree, x);
}
}
}
class SplayMap {
constructor() { this.root = null; this.size = 0; }
_find(key) {
let x = this.root, last = null;
while (x) {
last = x;
if (key === x.key) break;
x = key < x.key ? x.left : x.right;
}
if (last) splay(this, last);
return x;
}
get(key) { return this._find(keyOf(key))?.value; }
has(key) { return this._find(keyOf(key)) !== null; }
set(key, value) {
key = keyOf(key);
let x = this.root, parent = null;
while (x) {
parent = x;
if (key === x.key) {
x.value = value;
splay(this, x);
return this;
}
x = key < x.key ? x.left : x.right;
}
x = { key, value, left: null, right: null, parent };
if (!parent) this.root = x;
else if (key < parent.key) parent.left = x;
else parent.right = x;
this.size++;
splay(this, x);
return this;
}
delete(key) {
const x = this._find(keyOf(key));
if (!x) return false;
const left = x.left, right = x.right;
if (left) left.parent = null;
if (right) right.parent = null;
x.left = x.right = x.parent = null;
this.size--;
if (!left) this.root = right;
else {
this.root = left;
let max = left;
while (max.right) max = max.right;
splay(this, max);
this.root.right = right;
if (right) right.parent = this.root;
}
return true;
}
lowerBound(key) {
key = keyOf(key);
let x = this.root, last = null, best = null;
while (x) {
last = x;
if (x.key >= key) { best = x; x = x.left; }
else x = x.right;
}
if (last) splay(this, last);
return best ? [best.key, best.value] : null;
}
entries() {
const out = [], stack = [];
let x = this.root;
while (x || stack.length) {
while (x) { stack.push(x); x = x.left; }
x = stack.pop();
out.push([x.key, x.value]);
x = x.right;
}
return out;
}
}
function validate(tree) {
const seen = new Set();
const stack = tree.root ? [[tree.root, null, -Infinity, Infinity]] : [];
while (stack.length) {
const [x, parent, low, high] = stack.pop();
assert(!seen.has(x), "cycle or shared child");
seen.add(x);
assert.equal(x.parent, parent, "parent link");
assert(Number.isFinite(x.key) && low < x.key && x.key < high,
"strict ancestor bounds");
if (x.left) stack.push([x.left, x, low, x.key]);
if (x.right) stack.push([x.right, x, x.key, high]);
}
assert.equal(seen.size, tree.size, "reachable size");
}
function check(tree, oracle) {
validate(tree);
const sorted = [...oracle].sort((a, b) => a[0] - b[0]);
assert.deepEqual(tree.entries(), sorted);
assert.equal(tree.size, oracle.size);
}
function step(tree, oracle, op, key) {
if (op === "set") {
const value = key === 0 ? undefined : `v${key}`;
tree.set(key, value); oracle.set(key, value);
assert.equal(tree.root.key, key);
} else if (op === "delete") {
assert.equal(tree.delete(key), oracle.delete(key));
} else if (op === "get") {
assert.equal(tree.get(key), oracle.get(key));
if (oracle.has(key)) assert.equal(tree.root.key, key);
} else if (op === "has") {
assert.equal(tree.has(key), oracle.has(key));
} else {
const expected = [...oracle].sort((a, b) => a[0] - b[0])
.find(entry => entry[0] >= key) ?? null;
assert.deepEqual(tree.lowerBound(key), expected);
}
check(tree, oracle);
}
const alphabet = ["set", "get", "has", "delete", "lowerBound"]
.flatMap(op => [-1, 0, 1].map(key => [op, key]));
let histories = 0;
function visit(prefix) {
if (prefix.length) {
const tree = new SplayMap(), oracle = new Map();
for (const [op, key] of prefix) step(tree, oracle, op, key);
histories++;
}
if (prefix.length === 4) return;
for (const action of alphabet) visit([...prefix, action]);
}
visit([]);
assert.equal(histories, 54240);
console.log(`all nonempty histories of length <= 4: ${histories}`);运行输出:
all nonempty histories of length <= 4: 54240
八、摊还对数成本,不能拿来承诺一次访问的延迟
伸展树不维持统一的高度上限,合法状态可以是一条链。示例八构造两万个节点的左链,这也是连续插入递增键、每次把新键伸展到根能够形成的形状。第一次查询最小键需要经过全部节点;伸展后立刻重复访问同一个键,第一步就命中。这里输出的是访问节点数,既没有计时,也没有和其他容器比较吞吐量。
原始论文的 访问引理与更新分析用势能处理整段操作序列:一个很贵的操作可以对应结构势能下降,摊还界不是随机输入假设,也不是每次调用的截止时间保证。从任意已有树分析时还要计入初始势能项;从空树开始的标准操作序列有对数级摊还界。单次访问仍可能线性,不能把这一点藏进“平均很快”四个字里。
对这份具体实现,查找、插入、删除和 lowerBound 的路径访问与伸展相连;entries 则明确需要完整遍历,耗时与节点数成正比,输出数组本身也占线性空间。核心修改操作采用迭代形式,不使用与高度等长的调用栈;完整快照和测试校验器有各自的额外空间。复杂度说明必须逐个 API 写,不能用一句统一标签覆盖整个类。
热点访问使得最近命中的节点位于根,是能从代码直接观察的局部事实。是否适合真实工作负载,还取决于访问分布、对象分配、运行时优化以及延迟目标。本文没有做基准测试,不给出“比 Map 更快”“适合一切缓存”之类结论;若业务要求严格的单次最坏延迟,应把这个需求放在选型之前。
"use strict";
const assert = require("node:assert/strict");
function rotate(tree, x) {
const p = x.parent;
const g = p.parent;
if (p.left === x) {
p.left = x.right;
if (x.right) x.right.parent = p;
x.right = p;
} else {
p.right = x.left;
if (x.left) x.left.parent = p;
x.left = p;
}
p.parent = x;
x.parent = g;
if (!g) tree.root = x;
else if (g.left === p) g.left = x;
else g.right = x;
}
function splay(tree, x) {
while (x.parent) {
const p = x.parent;
const g = p.parent;
if (!g) rotate(tree, x);
else if ((g.left === p) === (p.left === x)) {
rotate(tree, p);
rotate(tree, x);
} else {
rotate(tree, x);
rotate(tree, x);
}
}
}
const n = 20000;
let root = null;
for (let key = 0; key < n; key++) {
const x = { key, left: root, right: null, parent: null };
if (root) root.parent = x;
root = x;
}
const tree = { root };
let x = tree.root, visited = 0;
while (x) {
visited++;
if (x.key === 0) break;
x = x.left;
}
assert.equal(visited, n);
splay(tree, x);
assert.equal(tree.root.key, 0);
assert.equal(tree.root.parent, null);
assert.equal(tree.root.key === 0 ? 1 : 0, 1);
console.log(`first lookup visits=${visited}; immediate repeat visits=1`);运行输出:
first lookup visits=20000; immediate repeat visits=1
九、读取会改结构,快照也要说清楚复制了什么
最后看接口层容易被算法讨论淹没的细节。一个基于节点栈的惰性迭代器,如果在两次 next 之间允许 get 触发旋转,栈里保存的路径就可能失效。要支持这种接口,必须选择并实现明确的失效策略,不能因为调用的是读取方法就默认安全。
本文直接提供同步 entries 快照:方法调用时完成中序遍历,之后的插入、删除或伸展不会改变已经返回数组的成员关系。它不是标准 Map 的 entries 迭代器,也不是深拷贝。数组和每个二元组是新对象,但 value 若是对象,仍与调用者共享同一个引用。替换映射里的值,不会替换旧快照里的引用;修改那个旧对象,仍会在旧快照中可见。
示例九把这些区别写进断言,并确认非法键在全部公开键操作中均先报错、没有改变结构。返回 undefined 的合法记录、负零规范化、对象值引用以及失败输入的无副作用,都是接口正确性的一部分,不应留到业务接入时临时猜测。
"use strict";
const assert = require("node:assert/strict");
function keyOf(key) {
if (typeof key !== "number" || !Number.isFinite(key)) {
throw new TypeError("key must be a finite number");
}
return key === 0 ? 0 : key;
}
function rotate(tree, x) {
const p = x.parent;
const g = p.parent;
if (p.left === x) {
p.left = x.right;
if (x.right) x.right.parent = p;
x.right = p;
} else {
p.right = x.left;
if (x.left) x.left.parent = p;
x.left = p;
}
p.parent = x;
x.parent = g;
if (!g) tree.root = x;
else if (g.left === p) g.left = x;
else g.right = x;
}
function splay(tree, x) {
while (x.parent) {
const p = x.parent;
const g = p.parent;
if (!g) rotate(tree, x);
else if ((g.left === p) === (p.left === x)) {
rotate(tree, p);
rotate(tree, x);
} else {
rotate(tree, x);
rotate(tree, x);
}
}
}
class SplayMap {
constructor() { this.root = null; this.size = 0; }
_find(key) {
let x = this.root, last = null;
while (x) {
last = x;
if (key === x.key) break;
x = key < x.key ? x.left : x.right;
}
if (last) splay(this, last);
return x;
}
get(key) { return this._find(keyOf(key))?.value; }
has(key) { return this._find(keyOf(key)) !== null; }
set(key, value) {
key = keyOf(key);
let x = this.root, parent = null;
while (x) {
parent = x;
if (key === x.key) {
x.value = value;
splay(this, x);
return this;
}
x = key < x.key ? x.left : x.right;
}
x = { key, value, left: null, right: null, parent };
if (!parent) this.root = x;
else if (key < parent.key) parent.left = x;
else parent.right = x;
this.size++;
splay(this, x);
return this;
}
delete(key) {
const x = this._find(keyOf(key));
if (!x) return false;
const left = x.left, right = x.right;
if (left) left.parent = null;
if (right) right.parent = null;
x.left = x.right = x.parent = null;
this.size--;
if (!left) this.root = right;
else {
this.root = left;
let max = left;
while (max.right) max = max.right;
splay(this, max);
this.root.right = right;
if (right) right.parent = this.root;
}
return true;
}
lowerBound(key) {
key = keyOf(key);
let x = this.root, last = null, best = null;
while (x) {
last = x;
if (x.key >= key) { best = x; x = x.left; }
else x = x.right;
}
if (last) splay(this, last);
return best ? [best.key, best.value] : null;
}
entries() {
const out = [], stack = [];
let x = this.root;
while (x || stack.length) {
while (x) { stack.push(x); x = x.left; }
x = stack.pop();
out.push([x.key, x.value]);
x = x.right;
}
return out;
}
}
const m = new SplayMap();
const value = { count: 1 };
m.set(2, value).set(1, undefined).set(-0, "zero");
const snapshot = m.entries();
assert.equal(m.has(1), true); assert.equal(m.has(9), false);
m.set(2, { count: 9 }); m.delete(1); m.set(3, "new");
assert.deepEqual(snapshot.map(entry => entry[0]), [0, 1, 2]);
assert.equal(snapshot[2][1], value);
value.count = 7;
assert.equal(snapshot[2][1].count, 7);
assert.deepEqual(m.entries().map(entry => entry[0]), [0, 2, 3]);
const before = m.entries(), root = m.root;
for (const method of ["get", "has", "delete", "lowerBound", "set"]) {
assert.throws(() => m[method](NaN, "bad"), TypeError);
assert.deepEqual(m.entries(), before); assert.equal(m.root, root);
}
console.log("snapshot membership is fixed; object values stay shared");运行输出:
snapshot membership is fixed; object values stay shared
十、给 AI 补丁的最终审查清单
审完这样的实现,我会把结论拆成可追问的项目,而不是只写“算法正确”。第一,键域与返回值契约是否明确;第二,旋转是否维护全部双向连接;第三,同向双旋顺序是否正确;第四,成功和失败访问的调整对象是否一致;第五,删除是否先切断旧根、再满足 join 的跨树有序前提;第六,读取变形和快照引用语义是否有测试。
运行验证使用 Node.js v24.19.0。除正文九个独立示例外,附加测试穷尽五键的全部插入顺序与删除顺序组合,共一万四千四百组,并执行十万次固定种子的混合差分操作、数值边界与覆盖更新回归、长链的迭代遍历检查。运行结果只覆盖明确列出的输入族;真正的安全感来自这些证据能被别人重跑,而不是测试数字看上去够大。
让 AI 帮忙生成树结构的价值,在于它可以快速交出一个能够讨论的候选实现。合并之前,审查者仍要把“看起来像伸展树”分解成前提、状态转移和独立证据。一次正确返回不等于结构没有损伤,一棵有序树也不等于采用了正确的伸展策略。把这两层分别检查,代码审查才真正走出了示例演示。
参考资料
Sleator 与 Tarjan:Self-Adjusting Binary Search Trees,作者页面;论文全文,重点核对第 2、3 节。
ECMAScript:Map Objects,用于确认对照容器语义。
Node.js:Assert,用于严格断言与深相等检查。示例的实际运行版本见正文,不把在线文档版本当作运行记录。

