Update from HuggingChat
Browse files- README.md +2 -2
- index.html +293 -86
README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
---
|
| 2 |
-
title: "isValidBST —
|
| 3 |
emoji: 🧩
|
| 4 |
colorFrom: yellow
|
| 5 |
colorTo: pink
|
|
@@ -9,6 +9,6 @@ tags:
|
|
| 9 |
- huggingchat
|
| 10 |
---
|
| 11 |
|
| 12 |
-
# isValidBST —
|
| 13 |
|
| 14 |
Built with [HuggingChat](https://huggingface.co/chat).
|
|
|
|
| 1 |
---
|
| 2 |
+
title: "isValidBST — DFS vs BFS trace"
|
| 3 |
emoji: 🧩
|
| 4 |
colorFrom: yellow
|
| 5 |
colorTo: pink
|
|
|
|
| 9 |
- huggingchat
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# isValidBST — DFS vs BFS trace
|
| 13 |
|
| 14 |
Built with [HuggingChat](https://huggingface.co/chat).
|
index.html
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
<head>
|
| 4 |
<meta charset="utf-8" />
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
| 6 |
-
<title>isValidBST —
|
| 7 |
<style>
|
| 8 |
:root{
|
| 9 |
--bg:#070b14; --panel:#0d1524; --panel2:#101b2e; --line:#1e293b;
|
|
@@ -45,6 +45,13 @@
|
|
| 45 |
.presets{display:flex;flex-wrap:wrap;gap:6px;align-items:center;color:var(--dim);font-size:12px}
|
| 46 |
.presets button{padding:5px 9px;font-size:12px;background:#111c2e;border-color:#22344f;color:#b9c8de}
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
.grid{display:grid;grid-template-columns:1fr 330px;gap:14px;align-items:start}
|
| 49 |
@media (max-width:900px){.grid{grid-template-columns:1fr}}
|
| 50 |
aside{display:flex;flex-direction:column;gap:14px}
|
|
@@ -61,11 +68,13 @@
|
|
| 61 |
line.edge{stroke:#22334d;stroke-width:2;transition:stroke .18s}
|
| 62 |
line.edge.onpath{stroke:var(--amber);stroke-width:3}
|
| 63 |
|
|
|
|
| 64 |
g.node.active circle.node{stroke:var(--amber);stroke-width:3.5;fill:#2a1f05}
|
| 65 |
g.node.pass circle.node{stroke:var(--green);fill:#062a22}
|
| 66 |
g.node.done circle.node{stroke:#1f6f57;fill:#08201b;stroke-width:2}
|
| 67 |
g.node.fail circle.node{stroke:var(--red);stroke-width:3.5;fill:#3a0f12}
|
| 68 |
g.node.rejected circle.node{stroke:#fb923c;stroke-dasharray:5 4;fill:#2a1806}
|
|
|
|
| 69 |
g.node.active text.iv{fill:var(--amber)}
|
| 70 |
g.node.pass text.iv{fill:var(--green)}
|
| 71 |
g.node.done text.iv{fill:#3f8e77}
|
|
@@ -88,10 +97,13 @@
|
|
| 88 |
.verdict.bad{background:rgba(248,113,113,.13);color:var(--red);border:1px solid rgba(248,113,113,.4)}
|
| 89 |
|
| 90 |
.stack{display:flex;flex-direction:column-reverse;gap:5px;min-height:60px;max-height:230px;overflow:auto}
|
|
|
|
| 91 |
.frame{font:12px/1.3 ui-monospace,Menlo,monospace;padding:6px 9px;border-radius:8px;
|
| 92 |
background:#0a1322;border:1px solid #182a44;color:#a9bcd6;white-space:nowrap}
|
| 93 |
.frame.top{background:#2a1f05;border-color:var(--amber);color:#ffe6a8}
|
|
|
|
| 94 |
.frame .none{color:#7c8da6;font-style:italic}
|
|
|
|
| 95 |
|
| 96 |
.log{max-height:220px;overflow:auto;font:12px/1.5 ui-monospace,Menlo,monospace}
|
| 97 |
.logline{padding:3px 7px;border-radius:6px;color:#8195b1;white-space:pre-wrap;word-break:break-word}
|
|
@@ -101,7 +113,7 @@
|
|
| 101 |
|
| 102 |
.code{font:12.5px/1.55 ui-monospace,Menlo,monospace;margin:0;padding:8px 9px;background:#0a1322;
|
| 103 |
border:1px solid #16233a;border-radius:9px;overflow:auto;color:#8fa4c0}
|
| 104 |
-
.code .ln{display:block;padding:0 6px;border-left:2px solid transparent;border-radius:4px}
|
| 105 |
.code .ln.hi{background:#233457;color:#fff;border-left-color:var(--amber)}
|
| 106 |
.legend{margin-top:11px;color:var(--dim);font-size:12px;display:flex;flex-wrap:wrap;gap:14px}
|
| 107 |
.legend b{color:#a9bcd6;font-weight:600}
|
|
@@ -111,9 +123,10 @@
|
|
| 111 |
<body>
|
| 112 |
<div class="wrap">
|
| 113 |
<header>
|
| 114 |
-
<h1>isValidBST <span>·
|
| 115 |
-
<p>
|
| 116 |
-
a node's value becomes <b>maxVal</b> for its left subtree
|
|
|
|
| 117 |
</header>
|
| 118 |
|
| 119 |
<div class="card inputrow">
|
|
@@ -136,6 +149,13 @@
|
|
| 136 |
|
| 137 |
<div class="grid">
|
| 138 |
<section class="card">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
<div class="status" id="status"></div>
|
| 140 |
<div class="svgwrap"><svg id="tree" viewBox="0 0 400 300" preserveAspectRatio="xMidYMin meet"></svg></div>
|
| 141 |
<div class="controls">
|
|
@@ -147,18 +167,18 @@
|
|
| 147 |
<label class="speed">delay <input type="range" id="speed" min="120" max="1500" step="20" value="650" /></label>
|
| 148 |
</div>
|
| 149 |
<div class="legend">
|
| 150 |
-
<span><span class="dot" style="background:#fbbf24"></span><b>
|
|
|
|
| 151 |
<span><span class="dot" style="background:#34d399"></span><b>in window</b></span>
|
| 152 |
<span><span class="dot" style="background:#f87171"></span><b>window violated</b></span>
|
| 153 |
-
<span><span class="dot" style="background:#fb923c"></span><b>rejected</b> (a descendant failed)</span>
|
| 154 |
<span>label under a node = its <code>(minVal, maxVal)</code></span>
|
| 155 |
</div>
|
| 156 |
</section>
|
| 157 |
|
| 158 |
<aside>
|
| 159 |
-
<div class="card"><h2>Call stack</h2><div class="stack" id="stack"></div></div>
|
| 160 |
<div class="card"><h2>Trace</h2><div class="log" id="log"></div></div>
|
| 161 |
-
<div class="card"><h2>_isValid</h2><pre class="code" id="code"></pre></div>
|
| 162 |
</aside>
|
| 163 |
</div>
|
| 164 |
</div>
|
|
@@ -170,32 +190,57 @@
|
|
| 170 |
const R = 24, XGAP = 86, YGAP = 94, PAD = 58;
|
| 171 |
const $ = id => document.getElementById(id);
|
| 172 |
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
const fmt = v => v === Infinity ? '+∞' : v === -Infinity ? '−∞' : String(v);
|
|
|
|
| 186 |
const svgEl = (tag, attrs) => {
|
| 187 |
const e = document.createElementNS(NS, tag);
|
| 188 |
for (const k in attrs) e.setAttribute(k, attrs[k]);
|
| 189 |
return e;
|
| 190 |
};
|
| 191 |
|
| 192 |
-
// ---------- state ----------
|
|
|
|
| 193 |
let tree = null;
|
| 194 |
let allNodes = [], edgeRefs = [], gEls = new Map(), ivEls = new Map(), valOf = new Map();
|
| 195 |
let steps = [], snaps = [], failVal = null;
|
| 196 |
let index = -1, timer = null, playing = false;
|
| 197 |
|
| 198 |
-
// ---------- parsing / building ----------
|
| 199 |
function parseTokens(text) {
|
| 200 |
return text.split(/[\s,]+/).filter(Boolean).map(tok => {
|
| 201 |
const t = tok.toLowerCase();
|
|
@@ -243,8 +288,8 @@
|
|
| 243 |
return { nodes: ns, edges: es, width: PAD * 2 + Math.max(0, col - 1) * XGAP, height: PAD * 2 + maxDepth * YGAP };
|
| 244 |
}
|
| 245 |
|
| 246 |
-
/
|
| 247 |
-
function
|
| 248 |
const out = [];
|
| 249 |
failVal = null;
|
| 250 |
(function rec(node, min, max, path, parentId, side) {
|
|
@@ -254,7 +299,7 @@
|
|
| 254 |
return true;
|
| 255 |
}
|
| 256 |
const here = [...path, node.id];
|
| 257 |
-
out.push({ k: "enter", id: node.id, min, max, path: here });
|
| 258 |
if (node.val <= min || node.val >= max) {
|
| 259 |
if (failVal === null) failVal = node.val;
|
| 260 |
out.push({ k: "fail", id: node.id, val: node.val, min, max, path: here });
|
|
@@ -270,11 +315,53 @@
|
|
| 270 |
out.push({ k: "return", id: node.id, val: rightOk, path: here, from: "child" });
|
| 271 |
return rightOk;
|
| 272 |
})(root, -Infinity, Infinity, [], null, null);
|
| 273 |
-
out.push({ k: "done", valid: failVal === null
|
| 274 |
return out;
|
| 275 |
}
|
| 276 |
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
const stack = [], labels = new Map(), snaps = [];
|
| 279 |
let path = [];
|
| 280 |
for (const s of list) {
|
|
@@ -308,20 +395,63 @@
|
|
| 308 |
}
|
| 309 |
snaps.push({
|
| 310 |
step: s,
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
labels:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
});
|
| 315 |
}
|
| 316 |
return snaps;
|
| 317 |
}
|
| 318 |
|
| 319 |
-
// ---------- drawing ----------
|
| 320 |
function draw() {
|
| 321 |
const svg = $("tree");
|
| 322 |
svg.innerHTML = "";
|
| 323 |
gEls = new Map(); ivEls = new Map(); valOf = new Map(); edgeRefs = [];
|
| 324 |
-
if (!tree) { svg.setAttribute("viewBox", "0 0 400 220"); return; }
|
| 325 |
|
| 326 |
const L = layout(tree);
|
| 327 |
allNodes = L.nodes;
|
|
@@ -347,24 +477,47 @@
|
|
| 347 |
}
|
| 348 |
}
|
| 349 |
|
| 350 |
-
// ---------- panels ----------
|
| 351 |
-
function
|
| 352 |
-
const box = $("stack");
|
|
|
|
| 353 |
box.innerHTML = "";
|
| 354 |
-
|
| 355 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
return;
|
| 357 |
}
|
| 358 |
-
|
|
|
|
|
|
|
| 359 |
const d = document.createElement("div");
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
box.appendChild(d);
|
| 367 |
});
|
|
|
|
|
|
|
|
|
|
| 368 |
}
|
| 369 |
|
| 370 |
function renderStatus(snap) {
|
|
@@ -372,22 +525,32 @@
|
|
| 372 |
if (!s) { el.innerHTML = '<span class="muted">Press ▶ Play (or Step ▶) to trace the recursion.</span>'; return; }
|
| 373 |
const v = s.id != null ? valOf.get(s.id) : null;
|
| 374 |
let html = "";
|
|
|
|
| 375 |
if (s.k === "done") {
|
| 376 |
html = s.valid
|
| 377 |
? '<span class="verdict ok">TRUE — every node respected its window → VALID BST</span>'
|
| 378 |
: `<span class="verdict bad">FALSE — node ${failVal} broke its window → NOT a BST</span>`;
|
| 379 |
-
} else if (
|
| 380 |
-
html = `<span class="call">_isValid(node=${v}, minVal=${fmt(s.min)}, maxVal=${fmt(s.max)})</span>`;
|
| 381 |
-
|
| 382 |
-
html = `<span class="call">check node=${v}: </span><span class="cmp
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
html =
|
| 389 |
-
|
| 390 |
-
html = `<span class="call">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
}
|
| 392 |
el.innerHTML = html;
|
| 393 |
}
|
|
@@ -400,10 +563,42 @@
|
|
| 400 |
});
|
| 401 |
}
|
| 402 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
function fillLog() {
|
| 404 |
const box = $("log");
|
| 405 |
box.innerHTML = "";
|
| 406 |
-
steps.forEach(
|
| 407 |
const d = document.createElement("div");
|
| 408 |
d.className = "logline" + (s.k === "fail" ? " no" : (s.k === "pass" ? " ok" : ""));
|
| 409 |
d.textContent = logText(s);
|
|
@@ -411,32 +606,20 @@
|
|
| 411 |
});
|
| 412 |
}
|
| 413 |
|
| 414 |
-
function logText(s) {
|
| 415 |
-
const v = s.id != null ? valOf.get(s.id) : null;
|
| 416 |
-
switch (s.k) {
|
| 417 |
-
case "enter": return `→ _isValid(${v}, min=${fmt(s.min)}, max=${fmt(s.max)})`;
|
| 418 |
-
case "pass": return ` ✓ ${fmt(s.min)} < ${v} < ${fmt(s.max)} — value stays in window`;
|
| 419 |
-
case "fail": return ` ✗ ${v} outside (${fmt(s.min)}, ${fmt(s.max)}) — return False`;
|
| 420 |
-
case "null-enter": return `→ _isValid(None, ${fmt(s.min)}, ${fmt(s.max)}) [${s.side} of ${valOf.get(s.parentId)}]`;
|
| 421 |
-
case "null-return": return ` ✓ empty child → True`;
|
| 422 |
-
case "return": return `← return ${s.val ? "True" : "False"}${v !== null ? " from " + v : ""}`;
|
| 423 |
-
case "done": return s.valid ? "result: True → VALID BST" : "result: False → NOT a BST";
|
| 424 |
-
default: return "";
|
| 425 |
-
}
|
| 426 |
-
}
|
| 427 |
-
|
| 428 |
function renderCode(s) {
|
| 429 |
const box = $("code");
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
|
|
|
|
|
|
| 433 |
).join("");
|
| 434 |
}
|
| 435 |
|
| 436 |
-
// ---------- apply a step ----------
|
| 437 |
function apply(i) {
|
| 438 |
index = i;
|
| 439 |
-
const snap = i >= 0 ? snaps[i] : {
|
| 440 |
|
| 441 |
for (const n of allNodes) {
|
| 442 |
const lab = snap.labels.get(n.id);
|
|
@@ -444,16 +627,18 @@
|
|
| 444 |
ivEls.get(n.id).textContent = lab ? `(${fmt(lab.min)}, ${fmt(lab.max)})` : "";
|
| 445 |
}
|
| 446 |
for (const e of edgeRefs) {
|
| 447 |
-
const on =
|
|
|
|
|
|
|
| 448 |
e.el.setAttribute("class", "edge" + (on ? " onpath" : ""));
|
| 449 |
}
|
| 450 |
-
|
| 451 |
renderStatus(snap);
|
| 452 |
renderLog(i);
|
| 453 |
renderCode(snap.step);
|
| 454 |
}
|
| 455 |
|
| 456 |
-
// ---------- playback ----------
|
| 457 |
const delay = () => +$("speed").value;
|
| 458 |
|
| 459 |
function stop() {
|
|
@@ -476,7 +661,16 @@
|
|
| 476 |
tick();
|
| 477 |
}
|
| 478 |
|
| 479 |
-
// ---------- load ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 480 |
function load(text) {
|
| 481 |
stop();
|
| 482 |
tree = buildTree(parseTokens(text));
|
|
@@ -484,22 +678,33 @@
|
|
| 484 |
if (!tree) {
|
| 485 |
steps = []; snaps = [];
|
| 486 |
apply(-1);
|
| 487 |
-
$("status").innerHTML = '<span class="muted">Empty tree —
|
|
|
|
| 488 |
return;
|
| 489 |
}
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
}
|
| 495 |
|
| 496 |
-
// ---------- wiring ----------
|
| 497 |
$("play").onclick = play;
|
| 498 |
$("next").onclick = () => { stop(); if (index < steps.length - 1) apply(index + 1); };
|
| 499 |
$("prev").onclick = () => { stop(); if (index > -1) apply(index - 1); };
|
| 500 |
$("reset").onclick = () => { stop(); apply(-1); };
|
| 501 |
$("load").onclick = () => load($("input").value);
|
| 502 |
$("input").addEventListener("keydown", e => { if (e.key === "Enter") load($("input").value); });
|
|
|
|
| 503 |
document.querySelectorAll(".presets button").forEach(b => {
|
| 504 |
b.onclick = () => { $("input").value = b.dataset.t; load(b.dataset.t); };
|
| 505 |
});
|
|
@@ -508,8 +713,10 @@
|
|
| 508 |
if (e.key === "ArrowRight") { stop(); if (index < steps.length - 1) apply(index + 1); }
|
| 509 |
if (e.key === "ArrowLeft") { stop(); if (index > -1) apply(index - 1); }
|
| 510 |
if (e.key === " ") { e.preventDefault(); play(); }
|
|
|
|
| 511 |
});
|
| 512 |
|
|
|
|
| 513 |
load($("input").value);
|
| 514 |
})();
|
| 515 |
</script>
|
|
|
|
| 3 |
<head>
|
| 4 |
<meta charset="utf-8" />
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
| 6 |
+
<title>isValidBST — DFS vs BFS trace</title>
|
| 7 |
<style>
|
| 8 |
:root{
|
| 9 |
--bg:#070b14; --panel:#0d1524; --panel2:#101b2e; --line:#1e293b;
|
|
|
|
| 45 |
.presets{display:flex;flex-wrap:wrap;gap:6px;align-items:center;color:var(--dim);font-size:12px}
|
| 46 |
.presets button{padding:5px 9px;font-size:12px;background:#111c2e;border-color:#22344f;color:#b9c8de}
|
| 47 |
|
| 48 |
+
.modebar{display:flex;flex-wrap:wrap;gap:12px;align-items:center;margin-bottom:12px}
|
| 49 |
+
.seg{display:inline-flex;background:#0a1322;border:1px solid var(--line);border-radius:11px;padding:3px;gap:3px}
|
| 50 |
+
.seg button{background:transparent;border:1px solid transparent;color:#93a7c4;padding:7px 13px;border-radius:8px;font-size:13px}
|
| 51 |
+
.seg button:hover{background:#16233a;color:#d7e3f5;border-color:transparent}
|
| 52 |
+
.seg button.on{background:#1d4ed8;border-color:#2563eb;color:#fff;font-weight:600}
|
| 53 |
+
.hint{color:var(--dim);font-size:12.5px;flex:1 1 260px;min-width:200px}
|
| 54 |
+
|
| 55 |
.grid{display:grid;grid-template-columns:1fr 330px;gap:14px;align-items:start}
|
| 56 |
@media (max-width:900px){.grid{grid-template-columns:1fr}}
|
| 57 |
aside{display:flex;flex-direction:column;gap:14px}
|
|
|
|
| 68 |
line.edge{stroke:#22334d;stroke-width:2;transition:stroke .18s}
|
| 69 |
line.edge.onpath{stroke:var(--amber);stroke-width:3}
|
| 70 |
|
| 71 |
+
g.node.queued circle.node{stroke:var(--blue);fill:#0a1a30}
|
| 72 |
g.node.active circle.node{stroke:var(--amber);stroke-width:3.5;fill:#2a1f05}
|
| 73 |
g.node.pass circle.node{stroke:var(--green);fill:#062a22}
|
| 74 |
g.node.done circle.node{stroke:#1f6f57;fill:#08201b;stroke-width:2}
|
| 75 |
g.node.fail circle.node{stroke:var(--red);stroke-width:3.5;fill:#3a0f12}
|
| 76 |
g.node.rejected circle.node{stroke:#fb923c;stroke-dasharray:5 4;fill:#2a1806}
|
| 77 |
+
g.node.queued text.iv{fill:#7ba6e0}
|
| 78 |
g.node.active text.iv{fill:var(--amber)}
|
| 79 |
g.node.pass text.iv{fill:var(--green)}
|
| 80 |
g.node.done text.iv{fill:#3f8e77}
|
|
|
|
| 97 |
.verdict.bad{background:rgba(248,113,113,.13);color:var(--red);border:1px solid rgba(248,113,113,.4)}
|
| 98 |
|
| 99 |
.stack{display:flex;flex-direction:column-reverse;gap:5px;min-height:60px;max-height:230px;overflow:auto}
|
| 100 |
+
.stack.row{flex-direction:row;flex-wrap:wrap;align-items:center;justify-content:flex-start}
|
| 101 |
.frame{font:12px/1.3 ui-monospace,Menlo,monospace;padding:6px 9px;border-radius:8px;
|
| 102 |
background:#0a1322;border:1px solid #182a44;color:#a9bcd6;white-space:nowrap}
|
| 103 |
.frame.top{background:#2a1f05;border-color:var(--amber);color:#ffe6a8}
|
| 104 |
+
.frame.queued{border-color:#2c4a78;color:#93b6e6;background:#0a1a30}
|
| 105 |
.frame .none{color:#7c8da6;font-style:italic}
|
| 106 |
+
.qcap{color:var(--dim);font-size:11px;margin-top:8px;letter-spacing:.05em}
|
| 107 |
|
| 108 |
.log{max-height:220px;overflow:auto;font:12px/1.5 ui-monospace,Menlo,monospace}
|
| 109 |
.logline{padding:3px 7px;border-radius:6px;color:#8195b1;white-space:pre-wrap;word-break:break-word}
|
|
|
|
| 113 |
|
| 114 |
.code{font:12.5px/1.55 ui-monospace,Menlo,monospace;margin:0;padding:8px 9px;background:#0a1322;
|
| 115 |
border:1px solid #16233a;border-radius:9px;overflow:auto;color:#8fa4c0}
|
| 116 |
+
.code .ln{display:block;padding:0 6px;border-left:2px solid transparent;border-radius:4px;white-space:pre}
|
| 117 |
.code .ln.hi{background:#233457;color:#fff;border-left-color:var(--amber)}
|
| 118 |
.legend{margin-top:11px;color:var(--dim);font-size:12px;display:flex;flex-wrap:wrap;gap:14px}
|
| 119 |
.legend b{color:#a9bcd6;font-weight:600}
|
|
|
|
| 123 |
<body>
|
| 124 |
<div class="wrap">
|
| 125 |
<header>
|
| 126 |
+
<h1>isValidBST <span>· DFS vs BFS traced step by step</span></h1>
|
| 127 |
+
<p>Both algorithms use the same invariant: every node must sit strictly inside the open window <code>(minVal, maxVal)</code>
|
| 128 |
+
handed down by its ancestors — a node's value becomes <b>maxVal</b> for its left subtree, <b>minVal</b> for its right subtree.
|
| 129 |
+
Only the <em>order</em> in which nodes are visited changes.</p>
|
| 130 |
</header>
|
| 131 |
|
| 132 |
<div class="card inputrow">
|
|
|
|
| 149 |
|
| 150 |
<div class="grid">
|
| 151 |
<section class="card">
|
| 152 |
+
<div class="modebar">
|
| 153 |
+
<div class="seg" id="seg">
|
| 154 |
+
<button data-m="dfs" class="on" aria-pressed="true">DFS · recursion</button>
|
| 155 |
+
<button data-m="bfs" aria-pressed="false">BFS · queue</button>
|
| 156 |
+
</div>
|
| 157 |
+
<span class="hint" id="modehint"></span>
|
| 158 |
+
</div>
|
| 159 |
<div class="status" id="status"></div>
|
| 160 |
<div class="svgwrap"><svg id="tree" viewBox="0 0 400 300" preserveAspectRatio="xMidYMin meet"></svg></div>
|
| 161 |
<div class="controls">
|
|
|
|
| 167 |
<label class="speed">delay <input type="range" id="speed" min="120" max="1500" step="20" value="650" /></label>
|
| 168 |
</div>
|
| 169 |
<div class="legend">
|
| 170 |
+
<span><span class="dot" style="background:#fbbf24"></span><b>amber</b> = being explored (DFS path / BFS current)</span>
|
| 171 |
+
<span><span class="dot" style="background:#60a5fa"></span><b>blue</b> = waiting in the queue (BFS)</span>
|
| 172 |
<span><span class="dot" style="background:#34d399"></span><b>in window</b></span>
|
| 173 |
<span><span class="dot" style="background:#f87171"></span><b>window violated</b></span>
|
|
|
|
| 174 |
<span>label under a node = its <code>(minVal, maxVal)</code></span>
|
| 175 |
</div>
|
| 176 |
</section>
|
| 177 |
|
| 178 |
<aside>
|
| 179 |
+
<div class="card"><h2 id="panelTitle">Call stack</h2><div class="stack" id="stack"></div><div class="qcap" id="qcap"></div></div>
|
| 180 |
<div class="card"><h2>Trace</h2><div class="log" id="log"></div></div>
|
| 181 |
+
<div class="card"><h2 id="codeTitle">DFS · _isValid</h2><pre class="code" id="code"></pre></div>
|
| 182 |
</aside>
|
| 183 |
</div>
|
| 184 |
</div>
|
|
|
|
| 190 |
const R = 24, XGAP = 86, YGAP = 94, PAD = 58;
|
| 191 |
const $ = id => document.getElementById(id);
|
| 192 |
|
| 193 |
+
// ---------------- the two algorithms, verbatim ----------------
|
| 194 |
+
const CODE = {
|
| 195 |
+
dfs: [
|
| 196 |
+
'def isValidBST(root):',
|
| 197 |
+
' def _isValid(node, minVal, maxVal):',
|
| 198 |
+
' if not node: return True',
|
| 199 |
+
' if node.val <= minVal or node.val >= maxVal:',
|
| 200 |
+
' return False',
|
| 201 |
+
' return _isValid(node.left, minVal, node.val) and \\',
|
| 202 |
+
' _isValid(node.right, node.val, maxVal)',
|
| 203 |
+
' return _isValid(root, float("-inf"), float("inf"))'
|
| 204 |
+
],
|
| 205 |
+
bfs: [
|
| 206 |
+
'def isValidBST(root):',
|
| 207 |
+
' from collections import deque',
|
| 208 |
+
' if not root: return True',
|
| 209 |
+
' queue = deque([(root, -inf, +inf)])',
|
| 210 |
+
' while queue:',
|
| 211 |
+
' node, minVal, maxVal = queue.popleft()',
|
| 212 |
+
' if node.val <= minVal or node.val >= maxVal:',
|
| 213 |
+
' return False',
|
| 214 |
+
' if node.left: queue.append((node.left, minVal, node.val))',
|
| 215 |
+
' if node.right: queue.append((node.right, node.val, maxVal))',
|
| 216 |
+
' return True'
|
| 217 |
+
]
|
| 218 |
+
};
|
| 219 |
+
const LINE = {
|
| 220 |
+
dfs: { 'null-enter':2, 'null-return':2, 'enter':3, 'fail':4, 'pass':5, 'return':6, 'done':7 },
|
| 221 |
+
bfs: { 'enqueue':3, 'dequeue':5, 'pass':6, 'fail':7, 'enq-left':8, 'enq-right':9, 'done':10 }
|
| 222 |
+
};
|
| 223 |
+
const HINT = {
|
| 224 |
+
dfs: 'Depth-first recursion: each call owns its (minVal, maxVal) window and returns a bool back up the stack.',
|
| 225 |
+
bfs: 'Breadth-first iteration: a deque holds (node, minVal, maxVal) triples, checked level by level. Same windows, no recursion.'
|
| 226 |
+
};
|
| 227 |
|
| 228 |
const fmt = v => v === Infinity ? '+∞' : v === -Infinity ? '−∞' : String(v);
|
| 229 |
+
const esc = s => s.replace(/&/g, "&").replace(/</g, "<");
|
| 230 |
const svgEl = (tag, attrs) => {
|
| 231 |
const e = document.createElementNS(NS, tag);
|
| 232 |
for (const k in attrs) e.setAttribute(k, attrs[k]);
|
| 233 |
return e;
|
| 234 |
};
|
| 235 |
|
| 236 |
+
// ---------------- state ----------------
|
| 237 |
+
let mode = "dfs";
|
| 238 |
let tree = null;
|
| 239 |
let allNodes = [], edgeRefs = [], gEls = new Map(), ivEls = new Map(), valOf = new Map();
|
| 240 |
let steps = [], snaps = [], failVal = null;
|
| 241 |
let index = -1, timer = null, playing = false;
|
| 242 |
|
| 243 |
+
// ---------------- parsing / building ----------------
|
| 244 |
function parseTokens(text) {
|
| 245 |
return text.split(/[\s,]+/).filter(Boolean).map(tok => {
|
| 246 |
const t = tok.toLowerCase();
|
|
|
|
| 288 |
return { nodes: ns, edges: es, width: PAD * 2 + Math.max(0, col - 1) * XGAP, height: PAD * 2 + maxDepth * YGAP };
|
| 289 |
}
|
| 290 |
|
| 291 |
+
/* ---------------- DFS step generation (mirrors the recursive code) ---------------- */
|
| 292 |
+
function buildStepsDFS(root) {
|
| 293 |
const out = [];
|
| 294 |
failVal = null;
|
| 295 |
(function rec(node, min, max, path, parentId, side) {
|
|
|
|
| 299 |
return true;
|
| 300 |
}
|
| 301 |
const here = [...path, node.id];
|
| 302 |
+
out.push({ k: "enter", id: node.id, val: node.val, min, max, path: here });
|
| 303 |
if (node.val <= min || node.val >= max) {
|
| 304 |
if (failVal === null) failVal = node.val;
|
| 305 |
out.push({ k: "fail", id: node.id, val: node.val, min, max, path: here });
|
|
|
|
| 315 |
out.push({ k: "return", id: node.id, val: rightOk, path: here, from: "child" });
|
| 316 |
return rightOk;
|
| 317 |
})(root, -Infinity, Infinity, [], null, null);
|
| 318 |
+
out.push({ k: "done", valid: failVal === null });
|
| 319 |
return out;
|
| 320 |
}
|
| 321 |
|
| 322 |
+
/* ---------------- BFS step generation (mirrors the queue code) ---------------- */
|
| 323 |
+
function buildStepsBFS(root) {
|
| 324 |
+
const out = [];
|
| 325 |
+
failVal = null;
|
| 326 |
+
const queue = [{ node: root, min: -Infinity, max: Infinity }];
|
| 327 |
+
out.push({ k: "enqueue", id: root.id, val: root.val, min: -Infinity, max: Infinity });
|
| 328 |
+
while (queue.length) {
|
| 329 |
+
const { node, min, max } = queue.shift();
|
| 330 |
+
out.push({ k: "dequeue", id: node.id, val: node.val, min, max });
|
| 331 |
+
if (node.val <= min || node.val >= max) {
|
| 332 |
+
failVal = node.val;
|
| 333 |
+
out.push({ k: "fail", id: node.id, val: node.val, min, max });
|
| 334 |
+
out.push({ k: "done", valid: false });
|
| 335 |
+
return out;
|
| 336 |
+
}
|
| 337 |
+
out.push({ k: "pass", id: node.id, val: node.val, min, max });
|
| 338 |
+
|
| 339 |
+
if (node.left) {
|
| 340 |
+
const f = { node: node.left, min, max: node.val };
|
| 341 |
+
queue.push(f);
|
| 342 |
+
out.push({ k: "enq-left", id: node.left.id, val: node.left.val, min, max: node.val });
|
| 343 |
+
} else {
|
| 344 |
+
out.push({ k: "enq-left", id: null, parentId: node.id, min, max });
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
if (node.right) {
|
| 348 |
+
const f = { node: node.right, min: node.val, max };
|
| 349 |
+
queue.push(f);
|
| 350 |
+
out.push({ k: "enq-right", id: node.right.id, val: node.right.val, min: node.val, max });
|
| 351 |
+
} else {
|
| 352 |
+
out.push({ k: "enq-right", id: null, parentId: node.id, min, max });
|
| 353 |
+
}
|
| 354 |
+
}
|
| 355 |
+
out.push({ k: "done", valid: true });
|
| 356 |
+
return out;
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
/* ---------------- snapshots ---------------- */
|
| 360 |
+
function cloneLabels(labels) {
|
| 361 |
+
return new Map([...labels].map(([k, v]) => [k, Object.assign({}, v)]));
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
function buildSnapshotsDFS(list) {
|
| 365 |
const stack = [], labels = new Map(), snaps = [];
|
| 366 |
let path = [];
|
| 367 |
for (const s of list) {
|
|
|
|
| 395 |
}
|
| 396 |
snaps.push({
|
| 397 |
step: s,
|
| 398 |
+
frames: stack.map(f => Object.assign({}, f)),
|
| 399 |
+
current: null,
|
| 400 |
+
labels: cloneLabels(labels),
|
| 401 |
+
pathIds: path.slice(),
|
| 402 |
+
hotIds: []
|
| 403 |
+
});
|
| 404 |
+
}
|
| 405 |
+
return snaps;
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
function buildSnapshotsBFS(list) {
|
| 409 |
+
const queue = [], labels = new Map(), snaps = [];
|
| 410 |
+
let current = null;
|
| 411 |
+
for (const s of list) {
|
| 412 |
+
switch (s.k) {
|
| 413 |
+
case "enqueue":
|
| 414 |
+
queue.push({ id: s.id, min: s.min, max: s.max });
|
| 415 |
+
labels.set(s.id, { min: s.min, max: s.max, status: "queued" });
|
| 416 |
+
break;
|
| 417 |
+
case "dequeue": {
|
| 418 |
+
const f = queue.shift();
|
| 419 |
+
current = f && f.id === s.id ? f : { id: s.id, min: s.min, max: s.max };
|
| 420 |
+
labels.set(s.id, { min: s.min, max: s.max, status: "active" });
|
| 421 |
+
break;
|
| 422 |
+
}
|
| 423 |
+
case "pass":
|
| 424 |
+
labels.set(s.id, { min: s.min, max: s.max, status: "pass" });
|
| 425 |
+
break;
|
| 426 |
+
case "fail":
|
| 427 |
+
labels.set(s.id, { min: s.min, max: s.max, status: "fail" });
|
| 428 |
+
break;
|
| 429 |
+
case "enq-left":
|
| 430 |
+
case "enq-right":
|
| 431 |
+
if (s.id !== null) {
|
| 432 |
+
queue.push({ id: s.id, min: s.min, max: s.max });
|
| 433 |
+
labels.set(s.id, { min: s.min, max: s.max, status: "queued" });
|
| 434 |
+
}
|
| 435 |
+
break;
|
| 436 |
+
}
|
| 437 |
+
snaps.push({
|
| 438 |
+
step: s,
|
| 439 |
+
frames: queue.map(f => Object.assign({}, f)),
|
| 440 |
+
current: current ? Object.assign({}, current) : null,
|
| 441 |
+
labels: cloneLabels(labels),
|
| 442 |
+
pathIds: [],
|
| 443 |
+
hotIds: queue.map(f => f.id).concat(current && current.id !== null ? [current.id] : [])
|
| 444 |
});
|
| 445 |
}
|
| 446 |
return snaps;
|
| 447 |
}
|
| 448 |
|
| 449 |
+
// ---------------- drawing ----------------
|
| 450 |
function draw() {
|
| 451 |
const svg = $("tree");
|
| 452 |
svg.innerHTML = "";
|
| 453 |
gEls = new Map(); ivEls = new Map(); valOf = new Map(); edgeRefs = [];
|
| 454 |
+
if (!tree) { svg.setAttribute("viewBox", "0 0 400 220"); svg.style.minWidth = ""; return; }
|
| 455 |
|
| 456 |
const L = layout(tree);
|
| 457 |
allNodes = L.nodes;
|
|
|
|
| 477 |
}
|
| 478 |
}
|
| 479 |
|
| 480 |
+
// ---------------- panels ----------------
|
| 481 |
+
function renderFrames(snap) {
|
| 482 |
+
const box = $("stack"), cap = $("qcap");
|
| 483 |
+
box.className = "stack" + (mode === "bfs" ? " row" : "");
|
| 484 |
box.innerHTML = "";
|
| 485 |
+
$("panelTitle").textContent = mode === "dfs" ? "Call stack" : "Queue";
|
| 486 |
+
|
| 487 |
+
if (mode === "dfs") {
|
| 488 |
+
cap.textContent = snap.frames.length ? "bottom → top (innermost call last)" : "";
|
| 489 |
+
if (!snap.frames.length) {
|
| 490 |
+
box.innerHTML = '<div class="frame" style="color:#5b6b84">— stack empty —</div>';
|
| 491 |
+
return;
|
| 492 |
+
}
|
| 493 |
+
snap.frames.forEach((f, i) => {
|
| 494 |
+
const d = document.createElement("div");
|
| 495 |
+
d.className = "frame" + (i === snap.frames.length - 1 ? " top" : "");
|
| 496 |
+
const who = f.id === null ? '<span class="none">None</span>' : String(valOf.get(f.id));
|
| 497 |
+
d.innerHTML = `_isValid(${who}, ${fmt(f.min)}, ${fmt(f.max)})`;
|
| 498 |
+
box.appendChild(d);
|
| 499 |
+
});
|
| 500 |
return;
|
| 501 |
}
|
| 502 |
+
|
| 503 |
+
cap.textContent = snap.current || snap.frames.length ? "front → back (leftmost is checked next)" : "";
|
| 504 |
+
if (snap.current) {
|
| 505 |
const d = document.createElement("div");
|
| 506 |
+
d.className = "frame top";
|
| 507 |
+
const who = snap.current.id === null ? '<span class="none">None</span>' : String(valOf.get(snap.current.id));
|
| 508 |
+
d.innerHTML = `▶ (${who}, ${fmt(snap.current.min)}, ${fmt(snap.current.max)})`;
|
| 509 |
+
box.appendChild(d);
|
| 510 |
+
}
|
| 511 |
+
snap.frames.forEach((f, i) => {
|
| 512 |
+
const d = document.createElement("div");
|
| 513 |
+
d.className = "frame queued";
|
| 514 |
+
d.innerHTML = `(${valOf.get(f.id)}, ${fmt(f.min)}, ${fmt(f.max)})`;
|
| 515 |
+
if (i === 0) d.title = "front of the queue";
|
| 516 |
box.appendChild(d);
|
| 517 |
});
|
| 518 |
+
if (!snap.current && !snap.frames.length) {
|
| 519 |
+
box.innerHTML = '<div class="frame" style="color:#5b6b84">— queue empty —</div>';
|
| 520 |
+
}
|
| 521 |
}
|
| 522 |
|
| 523 |
function renderStatus(snap) {
|
|
|
|
| 525 |
if (!s) { el.innerHTML = '<span class="muted">Press ▶ Play (or Step ▶) to trace the recursion.</span>'; return; }
|
| 526 |
const v = s.id != null ? valOf.get(s.id) : null;
|
| 527 |
let html = "";
|
| 528 |
+
|
| 529 |
if (s.k === "done") {
|
| 530 |
html = s.valid
|
| 531 |
? '<span class="verdict ok">TRUE — every node respected its window → VALID BST</span>'
|
| 532 |
: `<span class="verdict bad">FALSE — node ${failVal} broke its window → NOT a BST</span>`;
|
| 533 |
+
} else if (mode === "dfs") {
|
| 534 |
+
if (s.k === "enter") html = `<span class="call">_isValid(node=${v}, minVal=${fmt(s.min)}, maxVal=${fmt(s.max)})</span>`;
|
| 535 |
+
else if (s.k === "pass") html = `<span class="call">check node=${v}: </span><span class="cmp ok">${fmt(s.min)} < ${v} < ${fmt(s.max)} ✓</span>`;
|
| 536 |
+
else if (s.k === "fail") html = `<span class="call">check node=${v}: </span><span class="cmp no">${v} <= ${fmt(s.min)} or ${v} >= ${fmt(s.max)} ✗</span>`;
|
| 537 |
+
else if (s.k === "null-enter") html = `<span class="call">_isValid(None, ${fmt(s.min)}, ${fmt(s.max)})</span> <span class="muted">— ${s.side} child of ${valOf.get(s.parentId)}</span>`;
|
| 538 |
+
else if (s.k === "null-return") html = '<span class="cmp ok">if not node → return True</span>';
|
| 539 |
+
else if (s.k === "return") html = `<span class="call">return ${s.val ? "True" : "False"}</span> <span class="muted">— unwinding ${v}</span>`;
|
| 540 |
+
} else {
|
| 541 |
+
if (s.k === "enqueue") html = `<span class="call">queue = deque([(node=${v}, ${fmt(s.min)}, ${fmt(s.max)})])</span>`;
|
| 542 |
+
else if (s.k === "dequeue") html = `<span class="call">popleft() → node=${v}, minVal=${fmt(s.min)}, maxVal=${fmt(s.max)}</span>`;
|
| 543 |
+
else if (s.k === "pass") html = `<span class="call">check node=${v}: </span><span class="cmp ok">${fmt(s.min)} < ${v} < ${fmt(s.max)} ✓</span> <span class="muted">— append its children</span>`;
|
| 544 |
+
else if (s.k === "fail") html = `<span class="call">check node=${v}: </span><span class="cmp no">${v} <= ${fmt(s.min)} or ${v} >= ${fmt(s.max)} ✗</span>`;
|
| 545 |
+
else if (s.k === "enq-left" || s.k === "enq-right") {
|
| 546 |
+
const side = s.k === "enq-left" ? "left" : "right";
|
| 547 |
+
if (s.id === null) html = `<span class="muted">no ${side} child of ${valOf.get(s.parentId)} → nothing appended</span>`;
|
| 548 |
+
else {
|
| 549 |
+
const lo = s.k === "enq-left" ? fmt(s.min) : String(valOf.get(s.parentId));
|
| 550 |
+
const hi = s.k === "enq-left" ? String(valOf.get(s.parentId)) : fmt(s.max);
|
| 551 |
+
html = `<span class="call">append (node=${v}, ${lo}, ${hi})</span> <span class="muted">— ${side} child of ${valOf.get(s.parentId)}</span>`;
|
| 552 |
+
}
|
| 553 |
+
}
|
| 554 |
}
|
| 555 |
el.innerHTML = html;
|
| 556 |
}
|
|
|
|
| 563 |
});
|
| 564 |
}
|
| 565 |
|
| 566 |
+
function logText(s) {
|
| 567 |
+
const v = s.id != null ? valOf.get(s.id) : null;
|
| 568 |
+
if (mode === "dfs") {
|
| 569 |
+
switch (s.k) {
|
| 570 |
+
case "enter": return `→ _isValid(${v}, min=${fmt(s.min)}, max=${fmt(s.max)})`;
|
| 571 |
+
case "pass": return ` ✓ ${fmt(s.min)} < ${v} < ${fmt(s.max)} — value stays in window`;
|
| 572 |
+
case "fail": return ` ✗ ${v} outside (${fmt(s.min)}, ${fmt(s.max)}) — return False`;
|
| 573 |
+
case "null-enter": return `→ _isValid(None, ${fmt(s.min)}, ${fmt(s.max)}) [${s.side} of ${valOf.get(s.parentId)}]`;
|
| 574 |
+
case "null-return": return ` ✓ empty child → True`;
|
| 575 |
+
case "return": return `← return ${s.val ? "True" : "False"}${v !== null ? " from " + v : ""}`;
|
| 576 |
+
case "done": return s.valid ? "result: True → VALID BST" : "result: False → NOT a BST";
|
| 577 |
+
}
|
| 578 |
+
return "";
|
| 579 |
+
}
|
| 580 |
+
switch (s.k) {
|
| 581 |
+
case "enqueue": return `queue = deque([(node=${v}, ${fmt(s.min)}, ${fmt(s.max)})])`;
|
| 582 |
+
case "dequeue": return `popleft() → (node=${v}, minVal=${fmt(s.min)}, maxVal=${fmt(s.max)})`;
|
| 583 |
+
case "pass": return ` ✓ ${fmt(s.min)} < ${v} < ${fmt(s.max)} — stays in window`;
|
| 584 |
+
case "fail": return ` ✗ ${v} outside (${fmt(s.min)}, ${fmt(s.max)}) — return False`;
|
| 585 |
+
case "enq-left":
|
| 586 |
+
return s.id === null
|
| 587 |
+
? ` no left child of ${valOf.get(s.parentId)} → nothing appended`
|
| 588 |
+
: ` append (node=${v}, ${fmt(s.min)}, ${valOf.get(s.parentId)})`;
|
| 589 |
+
case "enq-right":
|
| 590 |
+
return s.id === null
|
| 591 |
+
? ` no right child of ${valOf.get(s.parentId)} → nothing appended`
|
| 592 |
+
: ` append (node=${v}, ${valOf.get(s.parentId)}, ${fmt(s.max)})`;
|
| 593 |
+
case "done": return s.valid ? "queue drained → result: True → VALID BST" : "result: False → NOT a BST";
|
| 594 |
+
}
|
| 595 |
+
return "";
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
function fillLog() {
|
| 599 |
const box = $("log");
|
| 600 |
box.innerHTML = "";
|
| 601 |
+
steps.forEach(s => {
|
| 602 |
const d = document.createElement("div");
|
| 603 |
d.className = "logline" + (s.k === "fail" ? " no" : (s.k === "pass" ? " ok" : ""));
|
| 604 |
d.textContent = logText(s);
|
|
|
|
| 606 |
});
|
| 607 |
}
|
| 608 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 609 |
function renderCode(s) {
|
| 610 |
const box = $("code");
|
| 611 |
+
$("codeTitle").textContent = mode === "dfs" ? "DFS · _isValid" : "BFS · queue";
|
| 612 |
+
let hi = s ? (LINE[mode][s.k] !== undefined ? LINE[mode][s.k] : -1) : -1;
|
| 613 |
+
if (s && s.k === "done" && !s.valid && mode === "bfs") hi = 7;
|
| 614 |
+
box.innerHTML = CODE[mode].map((ln, i) =>
|
| 615 |
+
`<span class="ln${i === hi ? " hi" : ""}">${esc(ln)}</span>`
|
| 616 |
).join("");
|
| 617 |
}
|
| 618 |
|
| 619 |
+
// ---------------- apply a step ----------------
|
| 620 |
function apply(i) {
|
| 621 |
index = i;
|
| 622 |
+
const snap = i >= 0 ? snaps[i] : { frames: [], current: null, labels: new Map(), step: null, pathIds: [], hotIds: [] };
|
| 623 |
|
| 624 |
for (const n of allNodes) {
|
| 625 |
const lab = snap.labels.get(n.id);
|
|
|
|
| 627 |
ivEls.get(n.id).textContent = lab ? `(${fmt(lab.min)}, ${fmt(lab.max)})` : "";
|
| 628 |
}
|
| 629 |
for (const e of edgeRefs) {
|
| 630 |
+
const on = mode === "dfs"
|
| 631 |
+
? (snap.pathIds.indexOf(e.p) !== -1 && snap.pathIds.indexOf(e.c) !== -1)
|
| 632 |
+
: (snap.hotIds.indexOf(e.c) !== -1);
|
| 633 |
e.el.setAttribute("class", "edge" + (on ? " onpath" : ""));
|
| 634 |
}
|
| 635 |
+
renderFrames(snap);
|
| 636 |
renderStatus(snap);
|
| 637 |
renderLog(i);
|
| 638 |
renderCode(snap.step);
|
| 639 |
}
|
| 640 |
|
| 641 |
+
// ---------------- playback ----------------
|
| 642 |
const delay = () => +$("speed").value;
|
| 643 |
|
| 644 |
function stop() {
|
|
|
|
| 661 |
tick();
|
| 662 |
}
|
| 663 |
|
| 664 |
+
// ---------------- load ----------------
|
| 665 |
+
function rebuild() {
|
| 666 |
+
stop();
|
| 667 |
+
if (!tree) { steps = []; snaps = []; apply(-1); return; }
|
| 668 |
+
steps = mode === "dfs" ? buildStepsDFS(tree) : buildStepsBFS(tree);
|
| 669 |
+
snaps = mode === "dfs" ? buildSnapshotsDFS(steps) : buildSnapshotsBFS(steps);
|
| 670 |
+
fillLog();
|
| 671 |
+
apply(-1);
|
| 672 |
+
}
|
| 673 |
+
|
| 674 |
function load(text) {
|
| 675 |
stop();
|
| 676 |
tree = buildTree(parseTokens(text));
|
|
|
|
| 678 |
if (!tree) {
|
| 679 |
steps = []; snaps = [];
|
| 680 |
apply(-1);
|
| 681 |
+
$("status").innerHTML = '<span class="muted">Empty tree — both algorithms return True.</span>';
|
| 682 |
+
$("log").innerHTML = "";
|
| 683 |
return;
|
| 684 |
}
|
| 685 |
+
rebuild();
|
| 686 |
+
}
|
| 687 |
+
|
| 688 |
+
function setMode(m) {
|
| 689 |
+
if (m === mode) return;
|
| 690 |
+
mode = m;
|
| 691 |
+
[...$("seg").children].forEach(b => {
|
| 692 |
+
const on = b.dataset.m === mode;
|
| 693 |
+
b.classList.toggle("on", on);
|
| 694 |
+
b.setAttribute("aria-pressed", String(on));
|
| 695 |
+
});
|
| 696 |
+
$("modehint").textContent = HINT[mode];
|
| 697 |
+
rebuild();
|
| 698 |
}
|
| 699 |
|
| 700 |
+
// ---------------- wiring ----------------
|
| 701 |
$("play").onclick = play;
|
| 702 |
$("next").onclick = () => { stop(); if (index < steps.length - 1) apply(index + 1); };
|
| 703 |
$("prev").onclick = () => { stop(); if (index > -1) apply(index - 1); };
|
| 704 |
$("reset").onclick = () => { stop(); apply(-1); };
|
| 705 |
$("load").onclick = () => load($("input").value);
|
| 706 |
$("input").addEventListener("keydown", e => { if (e.key === "Enter") load($("input").value); });
|
| 707 |
+
[...$("seg").children].forEach(b => { b.onclick = () => setMode(b.dataset.m); });
|
| 708 |
document.querySelectorAll(".presets button").forEach(b => {
|
| 709 |
b.onclick = () => { $("input").value = b.dataset.t; load(b.dataset.t); };
|
| 710 |
});
|
|
|
|
| 713 |
if (e.key === "ArrowRight") { stop(); if (index < steps.length - 1) apply(index + 1); }
|
| 714 |
if (e.key === "ArrowLeft") { stop(); if (index > -1) apply(index - 1); }
|
| 715 |
if (e.key === " ") { e.preventDefault(); play(); }
|
| 716 |
+
if (e.key.toLowerCase() === "m") setMode(mode === "dfs" ? "bfs" : "dfs");
|
| 717 |
});
|
| 718 |
|
| 719 |
+
$("modehint").textContent = HINT[mode];
|
| 720 |
load($("input").value);
|
| 721 |
})();
|
| 722 |
</script>
|