/* ══════════════════════════════════════════════════════════════
DS-12 · 树、森林 ⇄ 二叉树 · 绘制与交互
渲染层:SVG(矢量图形 + 文字)——本页无图片素材,无 WebGL。
动效层:原生 rAF + 帧率无关一阶滤波,无第三方库。
核心机制「重挂」:转换不是两张图交叉淡化,而是同一批结点
被重新挂一遍 —— 非长子结点的入边,从"父亲"滑到"左邻兄弟",
同时结点滑向二叉树的槽位。这正是「右兄弟」三个字的几何含义。
══════════════════════════════════════════════════════════════ */
(function () {
'use strict';
const NS = 'http://www.w3.org/2000/svg';
const REDUCED = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
/* ── 小工具 ────────────────────────────────────────────── */
const el = (tag, attrs, parent) => {
const n = document.createElementNS(NS, tag);
if (attrs) for (const k in attrs) n.setAttribute(k, attrs[k]);
if (parent) parent.appendChild(n);
return n;
};
const clamp = (v, a, b) => (v < a ? a : v > b ? b : v);
const lerp = (a, b, t) => a + (b - a) * t;
const easeInOut = t => (t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
const cssVar = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
/* ── 数据 ──────────────────────────────────────────────── */
// 运行示例:10 个结点,度 3/3/2/1,叶子 6 个 —— 与题 3 的计数完全一致
const MAIN = {
id: 'A', ch: [
{ id: 'B', ch: [{ id: 'E' }, { id: 'F' }, { id: 'G' }] },
{ id: 'C', ch: [{ id: 'H' }, { id: 'I' }] },
{ id: 'D', ch: [{ id: 'J' }] }
]
};
// 森林:A(B,C) · D(E) · G —— 三棵树
const FOREST = [
{ id: 'A', ch: [{ id: 'B' }, { id: 'C' }] },
{ id: 'D', ch: [{ id: 'E' }] },
{ id: 'G', ch: [] }
];
function build(forest) {
const nodes = [], byId = {};
function create(spec, parent) {
const n = {
id: spec.id, label: spec.id,
parent: parent || null,
depth: parent ? parent.depth + 1 : 0,
children: (spec.ch || []).map(s => s.id),
firstChild: null, nextSibling: null, prevSib: null,
orderInParent: 0
};
nodes.push(n); byId[n.id] = n;
(spec.ch || []).forEach(s => create(s, n));
}
forest.forEach(f => create(f, null));
nodes.forEach(n => {
if (n.children.length) n.firstChild = byId[n.children[0]];
n.children.forEach((id, i) => {
const c = byId[id];
c.orderInParent = i;
if (i > 0) {
c.prevSib = byId[n.children[i - 1]];
c.prevSib.nextSibling = c;
}
});
});
const roots = forest.map(f => byId[f.id]);
for (let i = 0; i < roots.length - 1; i++) {
roots[i].nextSibling = roots[i + 1];
roots[i + 1].prevSib = roots[i];
}
nodes.forEach(n => {
n.isFirst = !n.prevSib;
n.originBin = n.isFirst ? n.parent : n.prevSib;
});
return { nodes, byId, roots };
}
/* ── 布局 ──────────────────────────────────────────────── */
// 树形:叶子占槽位,父结点取孩子的均值
function treeLayout(forest, byId) {
let slot = 0;
const place = spec => {
const n = byId[spec.id];
const kids = spec.ch || [];
if (!kids.length) { n.tx = slot++; return n.tx; }
let sum = 0;
kids.forEach(k => { sum += place(k); });
n.tx = sum / kids.length;
return n.tx;
};
forest.forEach(place);
}
// 二叉形:x = 中序槽位,y = 二叉深度(左=长子,右=兄弟)
function binaryLayout(root) {
const order = [];
(function ino(n) { if (!n) return; ino(n.firstChild); order.push(n); ino(n.nextSibling); })(root);
order.forEach((n, i) => { n.bx = i; });
(function dep(n, d) { if (!n) return; n.bDepth = d; dep(n.firstChild, d + 1); dep(n.nextSibling, d + 1); })(root, 0);
}
function normalize(nodes, keyX, keyY, outX, outY, box) {
let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
nodes.forEach(n => {
x0 = Math.min(x0, n[keyX]); x1 = Math.max(x1, n[keyX]);
y0 = Math.min(y0, n[keyY]); y1 = Math.max(y1, n[keyY]);
});
const dx = (x1 - x0) || 1, dy = (y1 - y0) || 1, p = box.pad;
nodes.forEach(n => {
n[outX] = p + ((n[keyX] - x0) / dx) * (box.w - p * 2);
n[outY] = p + ((n[keyY] - y0) / dy) * (box.h - p * 2);
});
}
/* ── 图 ────────────────────────────────────────────────── */
const C = {}; // 调色板常量,运行时从 token 读一次
class Diagram {
constructor(container, opts) {
this.opts = Object.assign({ w: 900, h: 620, pad: 84, r: 27, label: '', dark: false }, opts);
this.container = container;
this.bg = this.opts.dark ? C.ink : C.paper;
this.fg = this.opts.dark ? C.paper : C.ink;
const built = build(opts.forest);
this.nodes = built.nodes;
this.byId = built.byId;
this.root = built.byId[opts.forest[0].id];
treeLayout(opts.forest, built.byId);
binaryLayout(this.root);
const box = { w: this.opts.w, h: this.opts.h, pad: this.opts.pad };
normalize(this.nodes, 'tx', 'depth', 'sx', 'sy', box);
normalize(this.nodes, 'bx', 'bDepth', 'dx', 'dy', box);
this.nodes.forEach(n => {
n.cur = { x: n.sx, y: n.sy };
n.target = { x: n.sx, y: n.sy };
n.stagger = n.depth + 0.32 * n.orderInParent;
n.e = 0;
});
this.followers = [];
this.buildSvg();
this.t = 0;
}
buildSvg() {
const o = this.opts;
this.container.textContent = '';
this.container.style.setProperty('--ar', o.w + ' / ' + o.h);
const svg = el('svg', {
viewBox: `0 0 ${o.w} ${o.h}`,
role: 'img',
'aria-label': o.label
});
this.svg = svg;
this.gEdge = el('g', { class: 'edges' }, svg);
this.gMark = el('g', { class: 'marks' }, svg);
this.gNode = el('g', { class: 'nodes' }, svg);
this.edges = this.nodes.filter(n => n.originBin).map(n => {
const path = el('path', {
class: 'edge',
fill: 'none',
stroke: n.isFirst
? (this.opts.dark ? C.accentHi : C.child)
: (this.opts.dark ? C.sibOnInk : C.sib),
'stroke-width': 1.7,
'stroke-linecap': 'round'
}, this.gEdge);
return { node: n, path };
});
this.nodes.forEach(n => {
const g = el('g', { 'data-id': n.id }, this.gNode);
n.g = g;
n.circ = el('circle', {
r: o.r, fill: this.bg, stroke: this.fg, 'stroke-width': 1.7
}, g);
n.txt = el('text', {
'text-anchor': 'middle', dy: '.34em',
'font-size': Math.round(o.r * .8),
fill: this.fg,
'font-family': 'var(--font-mono)'
}, g);
n.txt.textContent = n.label;
n.ring = el('circle', {
r: o.r + 13, fill: 'none', stroke: C.accent,
'stroke-width': 2.2, opacity: 0
}, g);
});
svg.style.display = 'block';
svg.style.width = '100%';
this.container.appendChild(svg);
this.render(0, true);
this.paint();
}
/* t:0=树形,1=二叉形。逐结点错峰,重挂才读得出来 */
render(t, snap) {
this.t = t;
const span = 0.55, dmax = 0.45;
this.nodes.forEach(n => {
const d = Math.min(dmax, n.stagger * 0.115);
n.e = easeInOut(clamp((t - d) / span, 0, 1));
n.target.x = lerp(n.sx, n.dx, n.e);
n.target.y = lerp(n.sy, n.dy, n.e);
if (snap || REDUCED) { n.cur.x = n.target.x; n.cur.y = n.target.y; }
});
if (snap || REDUCED) this.paint();
}
tick(dt) {
const k = 1 - Math.exp(-16 * dt);
this.nodes.forEach(n => {
n.cur.x += (n.target.x - n.cur.x) * k;
n.cur.y += (n.target.y - n.cur.y) * k;
});
this.paint();
}
paint() {
const r = this.opts.r;
for (const n of this.nodes) {
n.g.setAttribute('transform', `translate(${n.cur.x.toFixed(2)} ${n.cur.y.toFixed(2)})`);
}
for (const { node: n, path } of this.edges) {
const o = n.originBin;
let x0, y0, op = 1;
if (n.parent) {
x0 = lerp(n.parent.cur.x, o.cur.x, n.e);
y0 = lerp(n.parent.cur.y, o.cur.y, n.e) + lerp(r, n.isFirst ? r : r * .72, n.e);
x0 += lerp(0, n.isFirst ? 0 : r * .72, n.e);
} else {
// 森林的第 2、3 棵树根:这条边是"新长出来的"
x0 = o.cur.x + lerp(0, n.isFirst ? 0 : r * .72, n.e);
y0 = o.cur.y + lerp(0, n.isFirst ? r : r * .72, n.e);
op = clamp(n.e * 1.8, 0, 1);
}
const x1 = n.cur.x, y1 = n.cur.y - r;
const dy = (y1 - y0) * .46;
path.setAttribute('d',
`M${x0.toFixed(1)} ${y0.toFixed(1)} C${x0.toFixed(1)} ${(y0 + dy).toFixed(1)} ` +
`${x1.toFixed(1)} ${(y1 - dy).toFixed(1)} ${x1.toFixed(1)} ${y1.toFixed(1)}`);
path.setAttribute('opacity', op.toFixed(2));
}
for (const f of this.followers) {
f.el.setAttribute('transform',
`translate(${(f.node.cur.x + (f.dx || 0)).toFixed(1)} ${(f.node.cur.y + (f.dy || 0)).toFixed(1)})`);
}
}
/* 圈 / 框:结点计数用(画出来,不是淡入) */
mark(kind, on) {
if (!this.marks) this.marks = { left: [], right: [], chain: [] };
this.marks[kind].forEach(({ shape }) => {
const i = this.followers.findIndex(f => f.el === shape);
if (i >= 0) this.followers.splice(i, 1);
shape.remove();
});
this.marks[kind] = [];
if (!on) return;
const r = this.opts.r;
let list;
if (kind === 'left') list = this.nodes.filter(n => !n.firstChild);
else if (kind === 'chain') {
list = [];
for (let n = this.root; n; n = n.nextSibling) list.push(n);
} else list = this.nodes.filter(n => !n.nextSibling);
list.forEach((n, i) => {
let shape;
if (kind === 'left') {
shape = el('circle', {
r: r + 12, fill: 'none', stroke: C.accent,
'stroke-width': 2.2, 'stroke-linecap': 'round', pathLength: 100
});
} else {
const s = kind === 'chain' ? r + 16 : r + 13;
shape = el('rect', {
x: -s, y: -s, width: s * 2, height: s * 2, fill: 'none', stroke: C.sib,
'stroke-width': 2.2, pathLength: 100
});
}
this.gMark.appendChild(shape);
if (!REDUCED) {
shape.style.strokeDasharray = '100';
shape.style.strokeDashoffset = '100';
shape.style.transition =
`stroke-dashoffset 620ms cubic-bezier(.16,1,.3,1) ${i * 70}ms`;
requestAnimationFrame(() => { shape.style.strokeDashoffset = '0'; });
}
this.marks[kind].push({ shape, node: n });
this.followers.push({ el: shape, node: n, dx: 0, dy: 0 });
});
this.paint();
}
/* 序号徽章:树的次序 vs 二叉树的次序 */
badges(treeOrder, btOrder) {
if (this.badgeG) this.badgeG.remove();
this.followers = this.followers.filter(f => !f.badge);
this.badgeG = el('g', {}, this.svg);
const same = treeOrder.join('') === btOrder.join('');
const r = this.opts.r;
const put = (id, i, color, dx) => {
const n = this.byId[id];
if (!n) return;
const g = el('g', {}, this.badgeG);
el('circle', { r: 13.5, fill: color }, g);
const t = el('text', {
'text-anchor': 'middle', dy: '.35em', 'font-size': 13, fill: C.paper,
'font-family': 'var(--font-mono)'
}, g);
t.textContent = String(i + 1);
this.followers.push({ el: g, node: n, dx, dy: -r - 24, badge: true });
};
if (same) {
treeOrder.forEach((id, i) => put(id, i, C.ink, 0));
} else {
treeOrder.forEach((id, i) => put(id, i, C.accent, -17));
btOrder.forEach((id, i) => put(id, i, C.sib, 17));
}
this.paint();
}
focus(id) {
for (const n of this.nodes) {
const on = n.id === id;
n.circ.setAttribute('fill', on ? C.accent : this.bg);
n.circ.setAttribute('stroke', on ? C.accent : this.fg);
n.txt.setAttribute('fill', on ? C.paper : this.fg);
n.ring.setAttribute('opacity', on ? 1 : 0);
}
}
}
/* ── 尺寸档位:窄屏换成更高的框,结点才看得清 ── */
function sizeFor(w, wide) {
if (w < 560) return { w: 620, h: 700, pad: 78, r: 30 };
return wide ? { w: 1100, h: 520, pad: 76, r: 26 } : { w: 900, h: 620, pad: 84, r: 27 };
}
function sizeForest(w) {
return w < 560
? { w: 620, h: 560, pad: 82, r: 32 }
: { w: 900, h: 520, pad: 92, r: 29 };
}
/* ═══════════════════════ 页面装配 ═══════════════════════ */
const mounted = []; // { el, spec, kind, sizeKey, build }
let hero, forest, trace, count;
function mount(m) {
const cw = m.el.clientWidth || 900;
const size = m.kind === 'forest' ? sizeForest(cw) : sizeFor(cw, m.wide);
const key = size.w;
if (m.diagram && m.sizeKey === key) return m.diagram;
const d = new Diagram(m.el, Object.assign({ forest: m.spec, label: m.label }, size));
m.diagram = d;
m.sizeKey = key;
return d;
}
function mountAll() {
mounted.forEach(m => { mount(m); });
}
function init() {
C.ink = cssVar('--ink');
C.paper = cssVar('--paper-hi');
C.accent = cssVar('--vermilion');
C.accentHi = cssVar('--vermilion-hi');
C.child = cssVar('--vermilion');
C.sib = cssVar('--indigo');
C.sibOnInk = cssVar('--indigo-onink');
C.muted = cssVar('--ink-3');
// OG 卡片:只借绘制器,不装交互
window.__mountOgDiagram = host => {
const d = new Diagram(host, {
forest: [MAIN], w: 760, h: 560, pad: 72, r: 34, dark: true,
label: '树转换成二叉树的示意图'
});
d.render(1, true);
return d;
};
if (!document.getElementById('heroStage')) {
const host = document.getElementById('ogDiagram');
if (host) window.__mountOgDiagram(host);
return;
}
const reg = (sel, spec, kind, label, wide) => {
const m = { el: document.querySelector(sel), spec, kind, label, wide };
mounted.push(m);
return mount(m);
};
hero = reg('[data-diagram="hero"]', [MAIN], 'main', '一棵树按左孩子右兄弟转换为二叉树的动态示意图', true);
forest = reg('[data-diagram="forest"]', FOREST, 'forest', '一片森林转换为二叉树的动态示意图');
trace = reg('[data-diagram="trace"]', [MAIN], 'main', '遍历次序标注图');
count = reg('[data-diagram="count"]', [MAIN], 'main', '无左孩子与无右孩子的结点标注图');
buildAnatomy(document.querySelector('[data-diagram="anatomy"]'));
/* ── 图 0 · 拖动条 ── */
const track = document.getElementById('scrubTrack');
const knob = document.getElementById('scrubKnob');
const fill = document.getElementById('scrubFill');
const hint = document.getElementById('scrubHint');
let auto = !REDUCED, idleUntil = 0, phase = 0;
function setT(t, fromUser) {
hero.render(t);
const pct = Math.round(t * 100);
knob.style.left = pct + '%';
fill.style.width = pct + '%';
track.setAttribute('aria-valuenow', String(pct));
track.setAttribute('aria-valuetext', pct + '%');
if (fromUser) {
auto = false;
idleUntil = performance.now() + 12000;
hint.textContent = '转换进度 ' + pct + '%';
}
}
const fromEvent = e => {
const r = track.getBoundingClientRect();
setT(clamp((e.clientX - r.left) / r.width, 0, 1), true);
};
let dragging = false, downX = 0;
track.addEventListener('pointerdown', e => {
downX = e.clientX;
dragging = false;
track.setPointerCapture(e.pointerId);
track.classList.add('is-drag');
});
track.addEventListener('pointermove', e => {
if (track.hasPointerCapture && track.hasPointerCapture(e.pointerId)) {
if (!dragging && Math.abs(e.clientX - downX) < 6) return;
dragging = true;
fromEvent(e);
} else if (e.pointerType === 'mouse') {
fromEvent(e);
}
});
const endDrag = e => {
if (!dragging && e.type === 'pointerup') fromEvent(e);
dragging = false;
track.classList.remove('is-drag');
try { track.releasePointerCapture(e.pointerId); } catch (_) { }
};
track.addEventListener('pointerup', endDrag);
track.addEventListener('pointercancel', endDrag);
track.addEventListener('keydown', e => {
const step = e.shiftKey ? 0.2 : 0.05;
let t = hero.t;
if (e.key === 'ArrowRight' || e.key === 'ArrowUp') t += step;
else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') t -= step;
else if (e.key === 'Home') t = 0;
else if (e.key === 'End') t = 1;
else return;
e.preventDefault();
setT(clamp(t, 0, 1), true);
});
// 邀请:把手柄点一圈再散掉
if (!REDUCED) {
const invite = document.createElement('div');
invite.className = 'scrub__invite';
track.appendChild(invite);
setTimeout(() => invite.classList.add('is-out'), 2400);
}
// 自动演示:无人操作、且在视野里时,慢慢折一次再展开
let inView = true;
if ('IntersectionObserver' in window) {
new IntersectionObserver(es => { inView = es[0].isIntersecting; }, { threshold: .1 })
.observe(document.getElementById('heroStage'));
}
(function autoTick(now) {
if (inView && !REDUCED && now > idleUntil) {
if (!auto) { auto = true; hint.textContent = '拖动 · 转换进度'; }
phase += 0.016 * 0.34;
setT(clamp((Math.sin(phase - Math.PI / 2) + 1) / 2, 0, 1), false);
}
requestAnimationFrame(autoTick);
})(performance.now());
setT(REDUCED ? 1 : 0, false);
/* ── 图 2 · 森林步进器 ── */
const NOTE = [
'一片森林:A 是第一棵树的根,D、G 各自成树。',
'把 D、G 两棵树的根,接到上一棵树根的右指针上——各树根互为兄弟。',
'每个结点的左指针指向它的长子;非长子的入边,从父亲滑到左邻兄弟。',
'折完。右链上的 3 个结点,就是原来的 3 棵树。'
];
const steps = Array.from(document.querySelectorAll('#forestStepper .step'));
const fNote = document.getElementById('forestNote');
const fRead = document.getElementById('forestReadout');
function goStep(i) {
steps.forEach((b, j) => {
b.classList.toggle('is-on', i === j);
b.setAttribute('aria-selected', i === j ? 'true' : 'false');
});
forest.render([0, 0.55, 0.86, 1][i], REDUCED);
fNote.textContent = NOTE[i];
forest.mark('left', false);
forest.mark('right', false);
forest.mark('chain', i === 3);
fRead.classList.toggle('is-dim', i !== 3);
}
steps.forEach(b => b.addEventListener('click', () => goStep(+b.dataset.step)));
goStep(0);
/* ── 图 3 · 遍历追踪 ── */
const modeBtns = Array.from(document.querySelectorAll('#traceBar .tg'));
const seqV1 = document.getElementById('seqV1');
const seqV2 = document.getElementById('seqV2');
const seqK1 = document.getElementById('seqK1');
const seqK2 = document.getElementById('seqK2');
const seqVerdict = document.getElementById('seqVerdict');
const traceNote = document.getElementById('traceNote');
let traceTimer = null;
const orders = computeOrders(MAIN);
function renderSeqs(mode, animated) {
const o = orders[mode];
const same = o.tree.join('') === o.bt.join('');
seqK1.textContent = o.nameTree;
seqK2.textContent = o.nameBt;
seqV1.innerHTML = '';
seqV2.innerHTML = '';
seqVerdict.textContent = '';
traceNote.textContent = o.note;
trace.focus(null);
trace.badges(o.tree, o.bt);
const cells = (host, arr) => arr.map(id => {
const s = document.createElement('span');
s.textContent = id;
host.appendChild(s);
return s;
});
const c1 = cells(seqV1, o.tree);
const c2 = cells(seqV2, o.bt);
clearInterval(traceTimer);
const verdict = same
? '两行逐字相同 —— 这就是「先根变先序、后根变中序」'
: '两行对不上 —— 层序与转换后二叉树的层序没有对应关系';
if (animated && !REDUCED) {
let i = 0;
const step = () => {
if (i >= o.tree.length) {
clearInterval(traceTimer);
seqVerdict.textContent = verdict;
trace.focus(null);
return;
}
trace.focus(o.tree[i]);
c1[i].classList.add('on');
c2[i].classList.add('on');
i++;
};
step();
traceTimer = setInterval(step, 240);
} else {
c1.forEach(c => c.classList.add('on'));
c2.forEach(c => c.classList.add('on'));
seqVerdict.textContent = verdict;
trace.focus(null);
}
return { tree: o.tree, bt: o.bt, same, btPost: o.btPost || null };
}
modeBtns.forEach(b => b.addEventListener('click', () => {
modeBtns.forEach(x => x.classList.toggle('is-on', x === b));
renderSeqs(b.dataset.mode, true);
}));
renderSeqs('pre', false);
/* ── 图 4 · 计数标注 ── */
const markBtns = Array.from(document.querySelectorAll('#markBar .tg'));
const markState = { left: true, right: true };
markBtns.forEach(b => {
b.setAttribute('aria-pressed', 'true');
b.addEventListener('click', () => {
const k = b.dataset.mark;
markState[k] = !markState[k];
b.classList.toggle('is-on', markState[k]);
b.setAttribute('aria-pressed', String(markState[k]));
count.mark(k, markState[k]);
});
});
count.mark('left', true);
count.mark('right', true);
chrome();
quiz();
/* ── 主循环 ── */
let last = performance.now();
(function frame(now) {
const dt = Math.min(0.05, (now - last) / 1000);
last = now;
for (const m of mounted) m.diagram.tick(dt);
requestAnimationFrame(frame);
})(performance.now());
/* ── 尺寸变化:跨档位才重建 ── */
let rt;
window.addEventListener('resize', () => {
clearTimeout(rt);
rt = setTimeout(() => {
const before = mounted.map(m => m.sizeKey).join(',');
mountAll();
const after = mounted.map(m => m.sizeKey).join(',');
if (before !== after) {
hero.render(hero.t, true);
forest.render(forest.t, true);
trace.render(1, true);
count.render(1, true);
count.mark('left', markState.left);
count.mark('right', markState.right);
}
}, 180);
});
/* ── 探针面(验证台架用) ── */
window.__probe = () => ({
reduced: REDUCED,
heroT: +hero.t.toFixed(3),
heroPos: hero.nodes.map(n => [n.id, +n.cur.x.toFixed(1), +n.cur.y.toFixed(1)]),
seq1: seqV1.textContent,
seq2: seqV2.textContent,
verdict: seqVerdict.textContent,
overflow: document.documentElement.scrollWidth - window.innerWidth,
marks: {
left: (count.marks && count.marks.left.length) || 0,
right: (count.marks && count.marks.right.length) || 0,
chain: (forest.marks && forest.marks.chain.length) || 0
},
quiz: window.__quizState ? window.__quizState() : null
});
window.__setMorph = t => {
auto = false;
idleUntil = performance.now() + 1e7;
setT(clamp(t, 0, 1), true);
hero.render(clamp(t, 0, 1), true);
hero.paint();
return window.__probe();
};
window.__runTrace = mode => renderSeqs(mode, false);
window.__orders = orders;
}
/* ── 遍历次序:树的算法与二叉树的算法各算一遍 ── */
function computeOrders(spec) {
const built = build([spec]);
const root = built.byId[spec.id];
const treePre = [], treePost = [], treeLevel = [];
(function pre(n) {
if (!n) return;
treePre.push(n.id);
n.children.forEach(id => pre(built.byId[id]));
})(root);
(function post(n) {
if (!n) return;
n.children.forEach(id => post(built.byId[id]));
treePost.push(n.id);
})(root);
(function level(n) {
const q = [n];
while (q.length) {
const x = q.shift();
treeLevel.push(x.id);
x.children.forEach(id => q.push(built.byId[id]));
}
})(root);
const btPre = [], btIn = [], btLevel = [], btPost = [];
(function bp(n) { if (!n) return; btPre.push(n.id); bp(n.firstChild); bp(n.nextSibling); })(root);
(function bi(n) { if (!n) return; bi(n.firstChild); btIn.push(n.id); bi(n.nextSibling); })(root);
(function bo(n) { if (!n) return; bo(n.firstChild); bo(n.nextSibling); btPost.push(n.id); })(root);
(function bl(n) {
const q = [n];
while (q.length) {
const x = q.shift();
if (!x) continue;
btLevel.push(x.id);
if (x.firstChild) q.push(x.firstChild);
if (x.nextSibling) q.push(x.nextSibling);
}
})(root);
return {
pre: { tree: treePre, bt: btPre, nameTree: '先根', nameBt: '先序', note: '先根遍历:先根,再依次进每棵子树。' },
post: { tree: treePost, bt: btIn, btPost, nameTree: '后根', nameBt: '中序', note: '后根遍历:先孩子们、最后根。到二叉树上,这是中序。' },
level: {
tree: treeLevel, bt: btLevel, nameTree: '层序', nameBt: '层序',
note: '层序:树按树的层走,二叉树按二叉树的层走。两条序列当场分家。'
}
};
}
/* ── 图 1 · 结点解剖 ── */
function buildAnatomy(host) {
const W = 900, H = 340;
const svg = el('svg', {
viewBox: `0 0 ${W} ${H}`, role: 'img',
'aria-label': '孩子兄弟表示法:左指针指向长子,右指针指向兄弟'
});
const gE = el('g', {}, svg), gN = el('g', {}, svg);
const R = 36;
const P = { v: [232, 112], u: [672, 112], c1: [132, 262], c2: [352, 262], c3: [548, 262] };
const edge = (a, b, kind, label) => {
const [x0, y0] = P[a], [x1, y1] = P[b];
const dy = (y1 - y0) * .46;
const p = el('path', {
class: 'an-edge', 'data-from': a,
d: `M${x0} ${y0} C${x0} ${y0 + dy} ${x1} ${y1 - dy} ${x1} ${y1}`,
fill: 'none', stroke: kind === 'child' ? C.child : C.sib,
'stroke-width': 2.2, 'stroke-linecap': 'round'
}, gE);
p.style.transition = 'opacity 180ms linear';
if (label) {
const t = el('text', {
x: (x0 + x1) / 2 + (kind === 'child' ? -30 : 16),
y: (y0 + y1) / 2 - 6,
'text-anchor': 'middle', 'font-size': 18,
'letter-spacing': '.08em',
fill: kind === 'child' ? C.child : C.sib,
class: 'an-lab', 'data-from': a,
'font-family': 'var(--font-mono)'
}, gE);
t.textContent = label;
t.style.transition = 'opacity 180ms linear';
}
};
edge('v', 'c1', 'child', 'firstChild');
edge('v', 'u', 'sib', 'nextSibling');
edge('c1', 'c2', 'sib', 'nextSibling');
edge('c2', 'c3', 'sib', null);
Object.keys(P).forEach(id => {
const [x, y] = P[id];
const g = el('g', {
class: 'an-node', 'data-id': id,
transform: `translate(${x} ${y})`, tabindex: '0', role: 'button',
'aria-label': '结点 ' + id + ' 的两根指针'
}, gN);
el('circle', { r: R, fill: C.paper, stroke: C.ink, 'stroke-width': 1.8 }, g);
const t = el('text', {
'text-anchor': 'middle', dy: '.34em', 'font-size': 26, fill: C.ink,
'font-family': 'var(--font-mono)'
}, g);
t.textContent = { c1: 'c₁', c2: 'c₂', c3: 'c₃' }[id] || id;
});
const note = el('text', {
x: W - 24, y: H - 22, 'text-anchor': 'end', 'font-size': 17,
'letter-spacing': '.14em', fill: C.muted, 'font-family': 'var(--font-mono)'
}, svg);
note.textContent = '左指针 → 长子 右指针 → 兄弟';
const light = id => {
svg.querySelectorAll('.an-edge, .an-lab').forEach(e => {
e.style.opacity = (!id || e.dataset.from === id) ? '1' : '.2';
});
};
svg.querySelectorAll('.an-node').forEach(n => {
const id = n.dataset.id;
n.addEventListener('pointerenter', () => light(id));
n.addEventListener('pointerleave', () => light(null));
n.addEventListener('focus', () => light(id));
n.addEventListener('blur', () => light(null));
});
host.textContent = '';
host.style.setProperty('--ar', W + ' / ' + H);
svg.style.display = 'block';
svg.style.width = '100%';
host.appendChild(svg);
}
/* ── 页面小机构 ── */
function chrome() {
const h1 = document.querySelector('.hero__title');
if (h1 && !REDUCED) {
Array.from(h1.childNodes).forEach(ch => {
if (ch.nodeType !== 3) return;
const frag = document.createDocumentFragment();
Array.from(ch.textContent).forEach((c, i) => {
const s = document.createElement('span');
s.className = 'w';
s.style.setProperty('--i', String(i));
s.textContent = c;
frag.appendChild(s);
});
h1.replaceChild(frag, ch);
});
}
const io = new IntersectionObserver(es => {
es.forEach(e => { if (e.isIntersecting) e.target.classList.add('is-in'); });
}, { threshold: .16 });
document.querySelectorAll('.sec, .creed').forEach(s => io.observe(s));
document.querySelector('.hero').classList.add('is-in');
const head = document.getElementById('siteHead');
const onScroll = () => head.classList.toggle('is-stuck', window.scrollY > 28);
window.addEventListener('scroll', onScroll, { passive: true });
onScroll();
const links = Array.from(document.querySelectorAll('.nav a'));
const map = new Map(links.map(a => [a.getAttribute('href').slice(1), a]));
const spy = new IntersectionObserver(es => {
es.forEach(e => {
if (!e.isIntersecting) return;
const a = map.get(e.target.id);
links.forEach(l => l.removeAttribute('aria-current'));
if (a) a.setAttribute('aria-current', 'true');
});
}, { rootMargin: '-45% 0px -50% 0px' });
document.querySelectorAll('main section[id]').forEach(s => spy.observe(s));
}
/* ── 判卷 ── */
const EXPL = {
1: '树转出的二叉树,根结点一定没有右孩子——因为根没有兄弟。它可能有左孩子(它有长子时)。答案 B。',
2: '树的后根 = 二叉树的中序,所以把后根序列原样抄过来就是中序序列:DEBFCA。看到“后根”就写“后序”,是本题唯一的陷阱。答案 B。',
3: '度≠0 的结点数 = 2+1+1 = 4,于是无右孩子的结点数 = 4+1 = 5。叶子数 = 10−4 = 6,两者不等,因为数的不是同一类结点。答案 B。'
};
function quiz() {
const form = document.getElementById('quizForm');
const result = document.getElementById('quizResult');
const gradeBtn = document.getElementById('gradeBtn');
const resetBtn = document.getElementById('resetBtn');
const qs = Array.from(form.querySelectorAll('.q'));
window.__quizState = () => qs.map(q => ({
q: q.dataset.q,
answer: q.dataset.answer,
picked: (q.querySelector('input:checked') || {}).value || null,
graded: q.hasAttribute('data-graded')
}));
form.addEventListener('submit', e => {
e.preventDefault();
let right = 0, answered = 0;
qs.forEach(q => {
const picked = q.querySelector('input:checked');
if (!picked) return;
answered++;
if (picked.value === q.dataset.answer) right++;
});
if (!answered) {
result.hidden = false;
result.classList.add('is-empty');
result.textContent = '还没有选任何答案 —— 至少选一项再判卷。';
return;
}
qs.forEach(q => {
const picked = q.querySelector('input:checked');
q.setAttribute('data-graded', '');
const ans = q.dataset.answer;
q.querySelectorAll('.opt').forEach(opt => {
const input = opt.querySelector('input');
opt.classList.toggle('is-correct', input.value === ans);
opt.classList.toggle('is-wrong', !!picked && input === picked && picked.value !== ans);
});
const expl = q.querySelector('.q__expl');
expl.classList.add('is-shown');
expl.innerHTML = picked
? EXPL[q.dataset.q]
: '这题没选。正确答案 ' + ans + ' —— ' + EXPL[q.dataset.q];
});
result.hidden = false;
result.classList.remove('is-empty');
const comment = right === 3 ? '全对。这张卡片过关了。'
: right === 2 ? '两题对。错的那题回上面的图再跑一遍。'
: '先回图 3、图 4 各跑一遍,再重做。';
result.innerHTML = '' + right + ' / 3 ' + comment +
' (回复答案也能判卷:1B 2B 3B)';
gradeBtn.disabled = true;
});
resetBtn.addEventListener('click', () => {
form.reset();
qs.forEach(q => {
q.removeAttribute('data-graded');
q.querySelectorAll('.opt').forEach(o => o.classList.remove('is-correct', 'is-wrong'));
q.querySelector('.q__expl').classList.remove('is-shown');
});
result.hidden = true;
result.classList.remove('is-empty');
gradeBtn.disabled = false;
});
}
/* ── 启动 ── */
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init, { once: true });
} else {
init();
}
})();