File size: 36,184 Bytes
3f76361
 
 
 
 
9d0e426
3f76361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d0e426
 
 
 
 
 
 
3f76361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d0e426
3f76361
 
 
 
 
9d0e426
3f76361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d0e426
3f76361
 
 
9d0e426
3f76361
9d0e426
3f76361
 
 
 
 
 
 
 
 
9d0e426
3f76361
 
 
 
 
 
 
 
 
9d0e426
 
 
 
3f76361
 
 
 
 
 
 
0de573a
 
 
 
 
 
 
 
 
 
3f76361
 
 
 
 
9d0e426
 
 
 
 
 
 
3f76361
 
 
 
 
 
 
 
 
 
 
9d0e426
 
3f76361
 
 
 
 
 
 
9d0e426
3f76361
9d0e426
3f76361
 
 
 
 
 
 
 
 
 
 
9d0e426
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f76361
 
9d0e426
3f76361
 
 
 
 
 
9d0e426
 
3f76361
 
 
 
 
9d0e426
3f76361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d0e426
 
3f76361
 
 
 
 
 
 
 
 
9d0e426
3f76361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d0e426
3f76361
 
 
9d0e426
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f76361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d0e426
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f76361
 
 
 
 
9d0e426
3f76361
 
 
 
9d0e426
3f76361
 
 
 
0de573a
3f76361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d0e426
 
 
 
3f76361
9d0e426
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f76361
 
9d0e426
 
 
3f76361
9d0e426
 
 
 
 
 
 
 
 
 
3f76361
 
9d0e426
 
 
3f76361
 
 
 
 
 
 
9d0e426
3f76361
 
 
 
9d0e426
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f76361
 
 
 
 
 
 
 
 
 
 
 
9d0e426
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f76361
 
 
9d0e426
3f76361
 
 
 
 
 
 
 
 
9d0e426
 
 
 
 
3f76361
 
 
9d0e426
3f76361
 
9d0e426
3f76361
 
 
 
 
 
 
9d0e426
 
 
3f76361
 
9d0e426
3f76361
 
 
 
 
9d0e426
3f76361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d0e426
 
 
 
 
 
 
 
 
 
3f76361
 
 
 
 
 
 
9d0e426
 
3f76361
 
9d0e426
 
 
 
 
 
 
 
 
 
 
 
 
3f76361
 
9d0e426
3f76361
 
 
 
 
 
9d0e426
3f76361
 
 
 
 
 
 
 
9d0e426
3f76361
 
9d0e426
3f76361
 
 
 
2e21927
3f76361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>isValidBST — DFS vs BFS trace</title>
<style>
  :root{
    --bg:#070b14; --panel:#0d1524; --panel2:#101b2e; --line:#1e293b;
    --txt:#e2e8f0; --dim:#8b9bb4;
    --green:#34d399; --red:#f87171; --amber:#fbbf24; --blue:#60a5fa;
  }
  *{box-sizing:border-box}
  html,body{height:100%}
  body{
    margin:0; color:var(--txt); background:radial-gradient(1200px 600px at 15% -10%, #14243f 0%, var(--bg) 55%) fixed;
    font:14px/1.45 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
  }
  .wrap{max-width:1240px;margin:0 auto;padding:22px 18px 40px}
  header h1{font-size:19px;margin:0 0 4px;letter-spacing:.2px;font-weight:650}
  header h1 span{color:var(--dim);font-weight:400}
  header p{margin:0 0 16px;color:var(--dim);font-size:13px}
  code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;background:#111c2f;border:1px solid var(--line);
       padding:1px 5px;border-radius:5px;font-size:12.5px;color:#c7d6ee}

  .card{background:linear-gradient(180deg,var(--panel2),var(--panel));border:1px solid var(--line);
        border-radius:14px;padding:14px 15px;box-shadow:0 10px 30px rgba(0,0,0,.35)}
  .card h2{margin:0 0 10px;font-size:11.5px;letter-spacing:.14em;text-transform:uppercase;color:var(--dim);font-weight:600}

  .inputrow{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-bottom:14px}
  .inputrow .grow{flex:1 1 260px;min-width:220px}
  input[type=text]{
    width:100%;background:#0a1424;border:1px solid var(--line);color:var(--txt);border-radius:9px;
    padding:9px 11px;font:13px/1.2 ui-monospace,Menlo,monospace;outline:none
  }
  input[type=text]:focus{border-color:#2f4a73;box-shadow:0 0 0 3px rgba(96,165,250,.12)}
  button{
    background:#16233a;border:1px solid #27395a;color:var(--txt);border-radius:9px;padding:8px 12px;
    font:13px/1 ui-sans-serif,system-ui;cursor:pointer;transition:.15s
  }
  button:hover{background:#1d2f4d;border-color:#3a5580}
  button:active{transform:translateY(1px)}
  button.primary{background:#1d4ed8;border-color:#2563eb}
  button.primary:hover{background:#2563eb}
  .presets{display:flex;flex-wrap:wrap;gap:6px;align-items:center;color:var(--dim);font-size:12px}
  .presets button{padding:5px 9px;font-size:12px;background:#111c2e;border-color:#22344f;color:#b9c8de}

  .modebar{display:flex;flex-wrap:wrap;gap:12px;align-items:center;margin-bottom:12px}
  .seg{display:inline-flex;background:#0a1322;border:1px solid var(--line);border-radius:11px;padding:3px;gap:3px}
  .seg button{background:transparent;border:1px solid transparent;color:#93a7c4;padding:7px 13px;border-radius:8px;font-size:13px}
  .seg button:hover{background:#16233a;color:#d7e3f5;border-color:transparent}
  .seg button.on{background:#1d4ed8;border-color:#2563eb;color:#fff;font-weight:600}
  .hint{color:var(--dim);font-size:12.5px;flex:1 1 260px;min-width:200px}

  .grid{display:grid;grid-template-columns:1fr 330px;gap:14px;align-items:start}
  @media (max-width:900px){.grid{grid-template-columns:1fr}}
  aside{display:flex;flex-direction:column;gap:14px}

  .svgwrap{overflow:auto;border-radius:10px;background:
     linear-gradient(0deg,rgba(255,255,255,.02),rgba(255,255,255,.02)),
     repeating-linear-gradient(0deg,transparent 0 27px,#0f1a2c 27px 28px);
     border:1px solid #16233a}
  svg{display:block;width:100%;height:auto;min-height:290px}

  circle.node{fill:#0b1426;stroke:#3d5273;stroke-width:2;transition:fill .18s,stroke .18s}
  text.val{fill:#dbe6f7;font:650 15px ui-monospace,Menlo,monospace;text-anchor:middle}
  text.iv{fill:#5f7391;font:11px ui-monospace,Menlo,monospace;text-anchor:middle;transition:fill .18s}
  line.edge{stroke:#22334d;stroke-width:2;transition:stroke .18s}
  line.edge.onpath{stroke:var(--amber);stroke-width:3}

  g.node.queued circle.node{stroke:var(--blue);fill:#0a1a30}
  g.node.active circle.node{stroke:var(--amber);stroke-width:3.5;fill:#2a1f05}
  g.node.pass circle.node{stroke:var(--green);fill:#062a22}
  g.node.done circle.node{stroke:#1f6f57;fill:#08201b;stroke-width:2}
  g.node.fail circle.node{stroke:var(--red);stroke-width:3.5;fill:#3a0f12}
  g.node.rejected circle.node{stroke:#fb923c;stroke-dasharray:5 4;fill:#2a1806}
  g.node.queued text.iv{fill:#7ba6e0}
  g.node.active text.iv{fill:var(--amber)}
  g.node.pass text.iv{fill:var(--green)}
  g.node.done text.iv{fill:#3f8e77}
  g.node.fail text.iv{fill:var(--red)}
  g.node.rejected text.iv{fill:#fb923c}

  .controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:12px}
  .controls .spacer{flex:1}
  .speed{display:flex;align-items:center;gap:8px;color:var(--dim);font-size:12px}
  input[type=range]{width:110px;accent-color:#2563eb}

  .status{min-height:44px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;
          font:13.5px/1.35 ui-monospace,Menlo,monospace;padding:10px 12px;border-radius:10px;
          background:#0a1322;border:1px solid #17253c;margin-bottom:12px}
  .status .call{color:#cddcf1}
  .status .cmp.ok{color:var(--green)} .status .cmp.no{color:var(--red)}
  .status .muted{color:var(--dim)}
  .verdict{font:650 13.5px/1.3 ui-sans-serif,system-ui;padding:5px 10px;border-radius:999px}
  .verdict.ok{background:rgba(52,211,153,.13);color:var(--green);border:1px solid rgba(52,211,153,.4)}
  .verdict.bad{background:rgba(248,113,113,.13);color:var(--red);border:1px solid rgba(248,113,113,.4)}

  .stack{display:flex;flex-direction:column-reverse;gap:5px;min-height:60px;max-height:230px;overflow:auto}
  .stack.row{flex-direction:row;flex-wrap:wrap;align-items:center;justify-content:flex-start}
  .frame{font:12px/1.3 ui-monospace,Menlo,monospace;padding:6px 9px;border-radius:8px;
         background:#0a1322;border:1px solid #182a44;color:#a9bcd6;white-space:nowrap}
  .frame.top{background:#2a1f05;border-color:var(--amber);color:#ffe6a8}
  .frame.queued{border-color:#2c4a78;color:#93b6e6;background:#0a1a30}
  .frame .none{color:#7c8da6;font-style:italic}
  .qcap{color:var(--dim);font-size:11px;margin-top:8px;letter-spacing:.05em}

  .log{max-height:220px;overflow:auto;font:12px/1.5 ui-monospace,Menlo,monospace}
  .logline{padding:3px 7px;border-radius:6px;color:#8195b1;white-space:pre-wrap;word-break:break-word}
  .logline.cur{background:#17253c;color:#e6eefc}
  .logline.ok{color:#5f9c8a}
  .logline.no{color:#d98c8c}

  .code{font:12.5px/1.55 ui-monospace,Menlo,monospace;margin:0;padding:8px 9px;background:#0a1322;
        border:1px solid #16233a;border-radius:9px;overflow:auto;color:#8fa4c0}
  .code .ln{display:block;padding:0 6px;border-left:2px solid transparent;border-radius:4px;white-space:pre}
  .code .ln.hi{background:#233457;color:#fff;border-left-color:var(--amber)}
  .legend{margin-top:11px;color:var(--dim);font-size:12px;display:flex;flex-wrap:wrap;gap:14px}
  .legend b{color:#a9bcd6;font-weight:600}
  .dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:5px;vertical-align:1px}
</style>
</head>
<body>
<div class="wrap">
  <header>
    <h1>isValidBST <span>· DFS vs BFS traced step by step</span></h1>
    <p>Both algorithms use the same invariant: every node must sit strictly inside the open window <code>(minVal, maxVal)</code>
       handed down by its ancestors — a node's value becomes <b>maxVal</b> for its left subtree, <b>minVal</b> for its right subtree.
       Only the <em>order</em> in which nodes are visited changes.</p>
  </header>

  <div class="card inputrow">
    <div class="grow"><input id="input" type="text" spellcheck="false" value="5,1,4,null,null,3,6" /></div>
    <button class="primary" id="load">Load tree</button>
    <div class="presets">
      <span>presets:</span>
      <button data-t="2,1,3">3 nodes ✓</button>
      <button data-t="5,1,4,null,null,3,6">7 nodes ✗</button>
      <button data-t="5,4,6,null,null,3,7">7 nodes ✗ deep</button>
      <button data-t="1,1">duplicate ✗</button>
      <button data-t="8,4,12,2,6,10,14,1,3,5,7,9,11,13,15">15 nodes ✓</button>
      <button data-t="50,25,75,12,37,62,87,6,18,31,43,56,68,81,93">15 nodes ✓ zig-zag</button>
      <button data-t="8,4,12,2,6,10,14,1,3,5,7,9,11,13,1">15 nodes ✗</button>
      <button data-t="160,80,240,40,120,200,280,20,60,100,140,180,220,260,300,10,30,50,70,90,110,130,150,170,190,210,230,250,270,290,310">31 nodes ✓</button>
      <button data-t="160,80,240,40,120,200,280,20,60,100,140,180,220,260,300,330,30,50,70,90,110,130,150,170,190,210,230,250,270,290,310">31 nodes ✗ wrong window</button>
      <button data-t="160,80,240,40,120,200,280,20,60,100,140,180,220,260,300,10,30,50,70,90,110,130,150,170,190,210,230,250,270,310,290">31 nodes ✗ swapped pair</button>
    </div>
  </div>

  <div class="grid">
    <section class="card">
      <div class="modebar">
        <div class="seg" id="seg">
          <button data-m="dfs" class="on" aria-pressed="true">DFS · recursion</button>
          <button data-m="bfs" aria-pressed="false">BFS · queue</button>
        </div>
        <span class="hint" id="modehint"></span>
      </div>
      <div class="status" id="status"></div>
      <div class="svgwrap"><svg id="tree" viewBox="0 0 400 300" preserveAspectRatio="xMidYMin meet"></svg></div>
      <div class="controls">
        <button class="primary" id="play">▶ Play</button>
        <button id="prev">◀ Step</button>
        <button id="next">Step ▶</button>
        <button id="reset">⟲ Reset</button>
        <span class="spacer"></span>
        <label class="speed">delay <input type="range" id="speed" min="120" max="1500" step="20" value="650" /></label>
      </div>
      <div class="legend">
        <span><span class="dot" style="background:#fbbf24"></span><b>amber</b> = being explored (DFS path / BFS current)</span>
        <span><span class="dot" style="background:#60a5fa"></span><b>blue</b> = waiting in the queue (BFS)</span>
        <span><span class="dot" style="background:#34d399"></span><b>in window</b></span>
        <span><span class="dot" style="background:#f87171"></span><b>window violated</b></span>
        <span>label under a node = its <code>(minVal, maxVal)</code></span>
      </div>
    </section>

    <aside>
      <div class="card"><h2 id="panelTitle">Call stack</h2><div class="stack" id="stack"></div><div class="qcap" id="qcap"></div></div>
      <div class="card"><h2>Trace</h2><div class="log" id="log"></div></div>
      <div class="card"><h2 id="codeTitle">DFS · _isValid</h2><pre class="code" id="code"></pre></div>
    </aside>
  </div>
</div>

<script>
(() => {
  "use strict";
  const NS = "http://www.w3.org/2000/svg";
  const R = 24, XGAP = 86, YGAP = 94, PAD = 58;
  const $ = id => document.getElementById(id);

  // ---------------- the two algorithms, verbatim ----------------
  const CODE = {
    dfs: [
      'def isValidBST(root):',
      '    def _isValid(node, minVal, maxVal):',
      '        if not node: return True',
      '        if node.val <= minVal or node.val >= maxVal:',
      '            return False',
      '        return _isValid(node.left, minVal, node.val) and \\',
      '               _isValid(node.right, node.val, maxVal)',
      '    return _isValid(root, float("-inf"), float("inf"))'
    ],
    bfs: [
      'def isValidBST(root):',
      '    from collections import deque',
      '    if not root: return True',
      '    queue = deque([(root, -inf, +inf)])',
      '    while queue:',
      '        node, minVal, maxVal = queue.popleft()',
      '        if node.val <= minVal or node.val >= maxVal:',
      '            return False',
      '        if node.left:  queue.append((node.left,  minVal, node.val))',
      '        if node.right: queue.append((node.right, node.val, maxVal))',
      '    return True'
    ]
  };
  const LINE = {
    dfs: { 'null-enter':2, 'null-return':2, 'enter':3, 'fail':4, 'pass':5, 'return':6, 'done':7 },
    bfs: { 'enqueue':3, 'dequeue':5, 'pass':6, 'fail':7, 'enq-left':8, 'enq-right':9, 'done':10 }
  };
  const HINT = {
    dfs: 'Depth-first recursion: each call owns its (minVal, maxVal) window and returns a bool back up the stack.',
    bfs: 'Breadth-first iteration: a deque holds (node, minVal, maxVal) triples, checked level by level. Same windows, no recursion.'
  };

  const fmt = v => v === Infinity ? '+∞' : v === -Infinity ? '−∞' : String(v);
  const esc = s => s.replace(/&/g, "&amp;").replace(/</g, "&lt;");
  const svgEl = (tag, attrs) => {
    const e = document.createElementNS(NS, tag);
    for (const k in attrs) e.setAttribute(k, attrs[k]);
    return e;
  };

  // ---------------- state ----------------
  let mode = "dfs";
  let tree = null;
  let allNodes = [], edgeRefs = [], gEls = new Map(), ivEls = new Map(), valOf = new Map();
  let steps = [], snaps = [], failVal = null;
  let index = -1, timer = null, playing = false;

  // ---------------- parsing / building ----------------
  function parseTokens(text) {
    return text.split(/[\s,]+/).filter(Boolean).map(tok => {
      const t = tok.toLowerCase();
      if (t === "null" || t === "#" || t === "_" || t === "n") return null;
      const n = Number(tok);
      return Number.isFinite(n) ? n : null;
    });
  }

  function buildTree(tokens) {
    if (!tokens.length || tokens[0] === null) return null;
    let uid = 0;
    const root = { val: tokens[0], left: null, right: null, id: uid++ };
    const queue = [root];
    let i = 1;
    while (queue.length && i < tokens.length) {
      const node = queue.shift();
      if (i < tokens.length) {
        const v = tokens[i++];
        if (v !== null) { node.left = { val: v, left: null, right: null, id: uid++ }; queue.push(node.left); }
      }
      if (i < tokens.length) {
        const v = tokens[i++];
        if (v !== null) { node.right = { val: v, left: null, right: null, id: uid++ }; queue.push(node.right); }
      }
    }
    return root;
  }

  function layout(root) {
    const ns = [], es = [];
    let col = 0, maxDepth = 0;
    (function dfs(n, d) {
      if (!n) return;
      maxDepth = Math.max(maxDepth, d);
      dfs(n.left, d + 1);
      n.col = col++; n.depth = d; ns.push(n);
      dfs(n.right, d + 1);
    })(root, 0);
    ns.forEach(n => { n.x = PAD + n.col * XGAP; n.y = PAD + n.depth * YGAP; });
    ns.forEach(n => {
      if (n.left) es.push({ p: n.id, c: n.left.id, a: n, b: n.left });
      if (n.right) es.push({ p: n.id, c: n.right.id, a: n, b: n.right });
    });
    return { nodes: ns, edges: es, width: PAD * 2 + Math.max(0, col - 1) * XGAP, height: PAD * 2 + maxDepth * YGAP };
  }

  /* ---------------- DFS step generation (mirrors the recursive code) ---------------- */
  function buildStepsDFS(root) {
    const out = [];
    failVal = null;
    (function rec(node, min, max, path, parentId, side) {
      if (node === null) {
        out.push({ k: "null-enter", min, max, parentId, side, path });
        out.push({ k: "null-return", min, max, path });
        return true;
      }
      const here = [...path, node.id];
      out.push({ k: "enter", id: node.id, val: node.val, min, max, path: here });
      if (node.val <= min || node.val >= max) {
        if (failVal === null) failVal = node.val;
        out.push({ k: "fail", id: node.id, val: node.val, min, max, path: here });
        out.push({ k: "return", id: node.id, val: false, path: here, from: "fail" });
        return false;
      }
      out.push({ k: "pass", id: node.id, val: node.val, min, max, path: here });
      if (!rec(node.left, min, node.val, here, node.id, "left")) {
        out.push({ k: "return", id: node.id, val: false, path: here, from: "child" });
        return false;
      }
      const rightOk = rec(node.right, node.val, max, here, node.id, "right");
      out.push({ k: "return", id: node.id, val: rightOk, path: here, from: "child" });
      return rightOk;
    })(root, -Infinity, Infinity, [], null, null);
    out.push({ k: "done", valid: failVal === null });
    return out;
  }

  /* ---------------- BFS step generation (mirrors the queue code) ---------------- */
  function buildStepsBFS(root) {
    const out = [];
    failVal = null;
    const queue = [{ node: root, min: -Infinity, max: Infinity }];
    out.push({ k: "enqueue", id: root.id, val: root.val, min: -Infinity, max: Infinity });
    while (queue.length) {
      const { node, min, max } = queue.shift();
      out.push({ k: "dequeue", id: node.id, val: node.val, min, max });
      if (node.val <= min || node.val >= max) {
        failVal = node.val;
        out.push({ k: "fail", id: node.id, val: node.val, min, max });
        out.push({ k: "done", valid: false });
        return out;
      }
      out.push({ k: "pass", id: node.id, val: node.val, min, max });

      if (node.left) {
        const f = { node: node.left, min, max: node.val };
        queue.push(f);
        out.push({ k: "enq-left", id: node.left.id, val: node.left.val, min, max: node.val });
      } else {
        out.push({ k: "enq-left", id: null, parentId: node.id, min, max });
      }

      if (node.right) {
        const f = { node: node.right, min: node.val, max };
        queue.push(f);
        out.push({ k: "enq-right", id: node.right.id, val: node.right.val, min: node.val, max });
      } else {
        out.push({ k: "enq-right", id: null, parentId: node.id, min, max });
      }
    }
    out.push({ k: "done", valid: true });
    return out;
  }

  /* ---------------- snapshots ---------------- */
  function cloneLabels(labels) {
    return new Map([...labels].map(([k, v]) => [k, Object.assign({}, v)]));
  }

  function buildSnapshotsDFS(list) {
    const stack = [], labels = new Map(), snaps = [];
    let path = [];
    for (const s of list) {
      if (s.path && s.path.length) path = s.path;
      switch (s.k) {
        case "enter":
          stack.push({ id: s.id, min: s.min, max: s.max });
          labels.set(s.id, { min: s.min, max: s.max, status: "active" });
          break;
        case "null-enter":
          stack.push({ id: null, min: s.min, max: s.max, parentId: s.parentId, side: s.side });
          break;
        case "null-return":
          stack.pop();
          break;
        case "pass":
          labels.set(s.id, { min: s.min, max: s.max, status: "pass" });
          break;
        case "fail":
          labels.set(s.id, { min: s.min, max: s.max, status: "fail" });
          break;
        case "return": {
          stack.pop();
          const l = labels.get(s.id);
          if (l) {
            if (s.val) l.status = "done";
            else if (l.status !== "fail") l.status = "rejected";
          }
          break;
        }
      }
      snaps.push({
        step: s,
        frames: stack.map(f => Object.assign({}, f)),
        current: null,
        labels: cloneLabels(labels),
        pathIds: path.slice(),
        hotIds: []
      });
    }
    return snaps;
  }

  function buildSnapshotsBFS(list) {
    const queue = [], labels = new Map(), snaps = [];
    let current = null;
    for (const s of list) {
      switch (s.k) {
        case "enqueue":
          queue.push({ id: s.id, min: s.min, max: s.max });
          labels.set(s.id, { min: s.min, max: s.max, status: "queued" });
          break;
        case "dequeue": {
          const f = queue.shift();
          current = f && f.id === s.id ? f : { id: s.id, min: s.min, max: s.max };
          labels.set(s.id, { min: s.min, max: s.max, status: "active" });
          break;
        }
        case "pass":
          labels.set(s.id, { min: s.min, max: s.max, status: "pass" });
          break;
        case "fail":
          labels.set(s.id, { min: s.min, max: s.max, status: "fail" });
          break;
        case "enq-left":
        case "enq-right":
          if (s.id !== null) {
            queue.push({ id: s.id, min: s.min, max: s.max });
            labels.set(s.id, { min: s.min, max: s.max, status: "queued" });
          }
          break;
      }
      snaps.push({
        step: s,
        frames: queue.map(f => Object.assign({}, f)),
        current: current ? Object.assign({}, current) : null,
        labels: cloneLabels(labels),
        pathIds: [],
        hotIds: queue.map(f => f.id).concat(current && current.id !== null ? [current.id] : [])
      });
    }
    return snaps;
  }

  // ---------------- drawing ----------------
  function draw() {
    const svg = $("tree");
    svg.innerHTML = "";
    gEls = new Map(); ivEls = new Map(); valOf = new Map(); edgeRefs = [];
    if (!tree) { svg.setAttribute("viewBox", "0 0 400 220"); svg.style.minWidth = ""; return; }

    const L = layout(tree);
    allNodes = L.nodes;
    svg.setAttribute("viewBox", `0 0 ${Math.max(L.width, 320)} ${Math.max(L.height, 240)}`);
    svg.style.minWidth = Math.min(Math.max(L.width, 320), 2400) + "px";

    for (const e of L.edges) {
      const line = svgEl("line", { x1: e.a.x, y1: e.a.y, x2: e.b.x, y2: e.b.y, class: "edge" });
      svg.appendChild(line);
      edgeRefs.push({ el: line, p: e.p, c: e.c });
    }
    for (const n of L.nodes) {
      valOf.set(n.id, n.val);
      const g = svgEl("g", { class: "node" });
      g.appendChild(svgEl("circle", { cx: n.x, cy: n.y, r: R, class: "node" }));
      const t = svgEl("text", { x: n.x, y: n.y + 5, class: "val" });
      t.textContent = n.val;
      g.appendChild(t);
      const iv = svgEl("text", { x: n.x, y: n.y + R + 15, class: "iv" });
      g.appendChild(iv);
      svg.appendChild(g);
      gEls.set(n.id, g); ivEls.set(n.id, iv);
    }
  }

  // ---------------- panels ----------------
  function renderFrames(snap) {
    const box = $("stack"), cap = $("qcap");
    box.className = "stack" + (mode === "bfs" ? " row" : "");
    box.innerHTML = "";
    $("panelTitle").textContent = mode === "dfs" ? "Call stack" : "Queue";

    if (mode === "dfs") {
      cap.textContent = snap.frames.length ? "bottom  →  top (innermost call last)" : "";
      if (!snap.frames.length) {
        box.innerHTML = '<div class="frame" style="color:#5b6b84">— stack empty —</div>';
        return;
      }
      snap.frames.forEach((f, i) => {
        const d = document.createElement("div");
        d.className = "frame" + (i === snap.frames.length - 1 ? " top" : "");
        const who = f.id === null ? '<span class="none">None</span>' : String(valOf.get(f.id));
        d.innerHTML = `_isValid(${who}, ${fmt(f.min)}, ${fmt(f.max)})`;
        box.appendChild(d);
      });
      return;
    }

    cap.textContent = snap.current || snap.frames.length ? "front → back (leftmost is checked next)" : "";
    if (snap.current) {
      const d = document.createElement("div");
      d.className = "frame top";
      const who = snap.current.id === null ? '<span class="none">None</span>' : String(valOf.get(snap.current.id));
      d.innerHTML = `▶ (${who}, ${fmt(snap.current.min)}, ${fmt(snap.current.max)})`;
      box.appendChild(d);
    }
    snap.frames.forEach((f, i) => {
      const d = document.createElement("div");
      d.className = "frame queued";
      d.innerHTML = `(${valOf.get(f.id)}, ${fmt(f.min)}, ${fmt(f.max)})`;
      if (i === 0) d.title = "front of the queue";
      box.appendChild(d);
    });
    if (!snap.current && !snap.frames.length) {
      box.innerHTML = '<div class="frame" style="color:#5b6b84">— queue empty —</div>';
    }
  }

  function renderStatus(snap) {
    const el = $("status"), s = snap.step;
    if (!s) { el.innerHTML = '<span class="muted">Press ▶ Play (or Step ▶) to trace the recursion.</span>'; return; }
    const v = s.id != null ? valOf.get(s.id) : null;
    let html = "";

    if (s.k === "done") {
      html = s.valid
        ? '<span class="verdict ok">TRUE — every node respected its window → VALID BST</span>'
        : `<span class="verdict bad">FALSE — node ${failVal} broke its window → NOT a BST</span>`;
    } else if (mode === "dfs") {
      if (s.k === "enter")      html = `<span class="call">_isValid(node=${v}, minVal=${fmt(s.min)}, maxVal=${fmt(s.max)})</span>`;
      else if (s.k === "pass")  html = `<span class="call">check node=${v}: </span><span class="cmp ok">${fmt(s.min)} &lt; ${v} &lt; ${fmt(s.max)} ✓</span>`;
      else if (s.k === "fail")  html = `<span class="call">check node=${v}: </span><span class="cmp no">${v} &lt;= ${fmt(s.min)} or ${v} &gt;= ${fmt(s.max)} ✗</span>`;
      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>`;
      else if (s.k === "null-return") html = '<span class="cmp ok">if not node → return True</span>';
      else if (s.k === "return")      html = `<span class="call">return ${s.val ? "True" : "False"}</span> <span class="muted">— unwinding ${v}</span>`;
    } else {
      if (s.k === "enqueue")      html = `<span class="call">queue = deque([(node=${v}, ${fmt(s.min)}, ${fmt(s.max)})])</span>`;
      else if (s.k === "dequeue") html = `<span class="call">popleft() → node=${v}, minVal=${fmt(s.min)}, maxVal=${fmt(s.max)}</span>`;
      else if (s.k === "pass")    html = `<span class="call">check node=${v}: </span><span class="cmp ok">${fmt(s.min)} &lt; ${v} &lt; ${fmt(s.max)} ✓</span> <span class="muted">— append its children</span>`;
      else if (s.k === "fail")    html = `<span class="call">check node=${v}: </span><span class="cmp no">${v} &lt;= ${fmt(s.min)} or ${v} &gt;= ${fmt(s.max)} ✗</span>`;
      else if (s.k === "enq-left" || s.k === "enq-right") {
        const side = s.k === "enq-left" ? "left" : "right";
        if (s.id === null) html = `<span class="muted">no ${side} child of ${valOf.get(s.parentId)} → nothing appended</span>`;
        else {
          const lo = s.k === "enq-left" ? fmt(s.min) : String(valOf.get(s.parentId));
          const hi = s.k === "enq-left" ? String(valOf.get(s.parentId)) : fmt(s.max);
          html = `<span class="call">append (node=${v}, ${lo}, ${hi})</span> <span class="muted">— ${side} child of ${valOf.get(s.parentId)}</span>`;
        }
      }
    }
    el.innerHTML = html;
  }

  function renderLog(i) {
    const box = $("log");
    [...box.children].forEach((c, k) => {
      c.classList.toggle("cur", k === i);
      if (k === i) c.scrollIntoView({ block: "nearest" });
    });
  }

  function logText(s) {
    const v = s.id != null ? valOf.get(s.id) : null;
    if (mode === "dfs") {
      switch (s.k) {
        case "enter":       return `→ _isValid(${v}, min=${fmt(s.min)}, max=${fmt(s.max)})`;
        case "pass":        return `  ✓ ${fmt(s.min)} < ${v} < ${fmt(s.max)} — value stays in window`;
        case "fail":        return `  ✗ ${v} outside (${fmt(s.min)}, ${fmt(s.max)}) — return False`;
        case "null-enter":  return `→ _isValid(None, ${fmt(s.min)}, ${fmt(s.max)})   [${s.side} of ${valOf.get(s.parentId)}]`;
        case "null-return": return `  ✓ empty child → True`;
        case "return":      return `← return ${s.val ? "True" : "False"}${v !== null ? " from " + v : ""}`;
        case "done":        return s.valid ? "result: True → VALID BST" : "result: False → NOT a BST";
      }
      return "";
    }
    switch (s.k) {
      case "enqueue":  return `queue = deque([(node=${v}, ${fmt(s.min)}, ${fmt(s.max)})])`;
      case "dequeue":  return `popleft() → (node=${v}, minVal=${fmt(s.min)}, maxVal=${fmt(s.max)})`;
      case "pass":     return `  ✓ ${fmt(s.min)} < ${v} < ${fmt(s.max)} — stays in window`;
      case "fail":     return `  ✗ ${v} outside (${fmt(s.min)}, ${fmt(s.max)}) — return False`;
      case "enq-left":
        return s.id === null
          ? `  no left child of ${valOf.get(s.parentId)} → nothing appended`
          : `  append (node=${v}, ${fmt(s.min)}, ${valOf.get(s.parentId)})`;
      case "enq-right":
        return s.id === null
          ? `  no right child of ${valOf.get(s.parentId)} → nothing appended`
          : `  append (node=${v}, ${valOf.get(s.parentId)}, ${fmt(s.max)})`;
      case "done":     return s.valid ? "queue drained → result: True → VALID BST" : "result: False → NOT a BST";
    }
    return "";
  }

  function fillLog() {
    const box = $("log");
    box.innerHTML = "";
    steps.forEach(s => {
      const d = document.createElement("div");
      d.className = "logline" + (s.k === "fail" ? " no" : (s.k === "pass" ? " ok" : ""));
      d.textContent = logText(s);
      box.appendChild(d);
    });
  }

  function renderCode(s) {
    const box = $("code");
    $("codeTitle").textContent = mode === "dfs" ? "DFS · _isValid" : "BFS · queue";
    let hi = s ? (LINE[mode][s.k] !== undefined ? LINE[mode][s.k] : -1) : -1;
    if (s && s.k === "done" && !s.valid && mode === "bfs") hi = 7;
    box.innerHTML = CODE[mode].map((ln, i) =>
      `<span class="ln${i === hi ? " hi" : ""}">${esc(ln)}</span>`
    ).join("");
  }

  // ---------------- apply a step ----------------
  function apply(i) {
    index = i;
    const snap = i >= 0 ? snaps[i] : { frames: [], current: null, labels: new Map(), step: null, pathIds: [], hotIds: [] };

    for (const n of allNodes) {
      const lab = snap.labels.get(n.id);
      gEls.get(n.id).setAttribute("class", "node" + (lab ? " " + lab.status : ""));
      ivEls.get(n.id).textContent = lab ? `(${fmt(lab.min)}, ${fmt(lab.max)})` : "";
    }
    for (const e of edgeRefs) {
      const on = mode === "dfs"
        ? (snap.pathIds.indexOf(e.p) !== -1 && snap.pathIds.indexOf(e.c) !== -1)
        : (snap.hotIds.indexOf(e.c) !== -1);
      e.el.setAttribute("class", "edge" + (on ? " onpath" : ""));
    }
    renderFrames(snap);
    renderStatus(snap);
    renderLog(i);
    renderCode(snap.step);
  }

  // ---------------- playback ----------------
  const delay = () => +$("speed").value;

  function stop() {
    playing = false;
    clearTimeout(timer);
    $("play").textContent = "▶ Play";
  }

  function tick() {
    if (index >= steps.length - 1) { stop(); return; }
    apply(index + 1);
    timer = setTimeout(tick, delay());
  }

  function play() {
    if (playing) { stop(); return; }
    if (index >= steps.length - 1) apply(-1);
    playing = true;
    $("play").textContent = "⏸ Pause";
    tick();
  }

  // ---------------- load ----------------
  function rebuild() {
    stop();
    if (!tree) { steps = []; snaps = []; apply(-1); return; }
    steps = mode === "dfs" ? buildStepsDFS(tree) : buildStepsBFS(tree);
    snaps = mode === "dfs" ? buildSnapshotsDFS(steps) : buildSnapshotsBFS(steps);
    fillLog();
    apply(-1);
  }

  function load(text) {
    stop();
    tree = buildTree(parseTokens(text));
    draw();
    if (!tree) {
      steps = []; snaps = [];
      apply(-1);
      $("status").innerHTML = '<span class="muted">Empty tree — both algorithms return True.</span>';
      $("log").innerHTML = "";
      return;
    }
    rebuild();
  }

  function setMode(m) {
    if (m === mode) return;
    mode = m;
    [...$("seg").children].forEach(b => {
      const on = b.dataset.m === mode;
      b.classList.toggle("on", on);
      b.setAttribute("aria-pressed", String(on));
    });
    $("modehint").textContent = HINT[mode];
    rebuild();
  }

  // ---------------- wiring ----------------
  $("play").onclick = play;
  $("next").onclick = () => { stop(); if (index < steps.length - 1) apply(index + 1); };
  $("prev").onclick = () => { stop(); if (index > -1) apply(index - 1); };
  $("reset").onclick = () => { stop(); apply(-1); };
  $("load").onclick = () => load($("input").value);
  $("input").addEventListener("keydown", e => { if (e.key === "Enter") load($("input").value); });
  [...$("seg").children].forEach(b => { b.onclick = () => setMode(b.dataset.m); });
  document.querySelectorAll(".presets button").forEach(b => {
    b.onclick = () => { $("input").value = b.dataset.t; load(b.dataset.t); };
  });
  document.addEventListener("keydown", e => {
    if (e.target.tagName === "INPUT" && e.target.type === "text") return;
    if (e.key === "ArrowRight") { stop(); if (index < steps.length - 1) apply(index + 1); }
    if (e.key === "ArrowLeft")  { stop(); if (index > -1) apply(index - 1); }
    if (e.key === " ") { e.preventDefault(); play(); }
    if (e.key.toLowerCase() === "m") setMode(mode === "dfs" ? "bfs" : "dfs");
  });

  $("modehint").textContent = HINT[mode];
  load($("input").value);
})();
</script>
</body>
</html>
<script data-huggingchat-badge="script">
(function () {
	try {
		if (document.querySelector("[data-huggingchat-badge]:not(script)")) return;
		var host = document.createElement("div");
		host.setAttribute("data-huggingchat-badge", "");
		var styles = [["all","initial"],["position","fixed"],["right","12px"],["bottom","12px"],["z-index","2147483647"],["display","block"],["visibility","visible"],["opacity","1"],["pointer-events","auto"],["width","auto"],["height","auto"],["margin","0"],["padding","0"],["max-width","none"],["max-height","none"],["transform","none"],["filter","none"],["clip-path","none"],["color-scheme","light"]];
		for (var i = 0; i < styles.length; i++) {
			host.style.setProperty(styles[i][0], styles[i][1], "important");
		}
		host.attachShadow({ mode: "closed" }).innerHTML = "<style>\n:host { all: initial; }\na {\n  display: flex;\n  align-items: center;\n  gap: 5px;\n  box-sizing: border-box;\n  height: 26px;\n  padding: 0 9px 0 7px;\n  border-radius: 999px;\n  border: 1px solid rgba(0, 0, 0, 0.07);\n  background: rgba(255, 255, 255, 0.92);\n  -webkit-backdrop-filter: saturate(180%) blur(8px);\n  backdrop-filter: saturate(180%) blur(8px);\n  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08), 0 6px 16px rgba(0, 0, 0, 0.06);\n  color: #111827;\n  font: 500 11px/1 ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif;\n  text-decoration: none;\n  white-space: nowrap;\n  opacity: 0.72;\n  transition: opacity 0.15s ease, transform 0.15s ease;\n}\na:hover, a:focus-visible { opacity: 1; transform: translateY(-1px); }\nsvg { width: 14px; height: 14px; flex: none; }\n@media print { a { display: none; } }\n<\/style><a href=\"https://huggingface.co/chat\" target=\"_blank\" rel=\"noopener noreferrer nofollow\"><svg viewBox=\"0 0 32 32\" fill=\"none\" aria-hidden=\"true\"><path d=\"M16.0006 25.9992C13.8266 25.999 11.7118 25.2901 9.97686 23.9799C8.2419 22.6698 6.98127 20.8298 6.38599 18.7388C5.79071 16.6478 5.89323 14.4198 6.678 12.3923C7.46278 10.3648 8.88705 8.64837 10.735 7.50308C12.5829 6.35779 14.7538 5.84606 16.9187 6.04544C19.0837 6.24481 21.1246 7.14442 22.7323 8.60795C24.34 10.0715 25.4268 12.0192 25.8281 14.1559C26.2293 16.2926 25.9232 18.5019 24.9561 20.449C24.7703 20.8042 24.7223 21.2155 24.8211 21.604L25.4211 23.8316C25.4803 24.0518 25.4805 24.2837 25.4216 24.5039C25.3627 24.7242 25.2468 24.925 25.0856 25.0862C24.9244 25.2474 24.7235 25.3633 24.5033 25.4222C24.283 25.4811 24.0512 25.4809 23.831 25.4217L21.6034 24.8217C21.2172 24.7248 20.809 24.7729 20.4558 24.9567C19.0683 25.6467 17.5457 26.0068 16.0006 26.0068V25.9992Z\" fill=\"currentColor\"/><path d=\"M9.62598 16.0013C9.62598 15.3799 10.1294 14.8765 10.7508 14.8765C11.3721 14.8765 11.8756 15.3799 11.8756 16.0013C11.8756 17.0953 12.3102 18.1448 13.0838 18.9184C13.8574 19.692 14.9069 20.1266 16.001 20.1267C17.095 20.1267 18.1445 19.692 18.9181 18.9184C19.6918 18.1448 20.1264 17.0953 20.1264 16.0013C20.1264 15.3799 20.6299 14.8765 21.2512 14.8765C21.8725 14.8765 22.3759 15.3799 22.3759 16.0013C22.3759 17.6921 21.7046 19.3137 20.509 20.5093C19.3134 21.7049 17.6918 22.3762 16.001 22.3762C14.3102 22.3762 12.6885 21.7049 11.4929 20.5093C10.2974 19.3137 9.62598 17.6921 9.62598 16.0013Z\" fill=\"#fff\"/><\/svg><span>Made with HuggingChat<\/span><\/a>";
		function attach() {
			var parent = document.body || document.documentElement;
			if (parent && host.parentNode !== parent) parent.appendChild(host);
		}
		attach();
		// Artifacts that rewrite document.body wholesale would drop the badge.
		if (document.body && typeof MutationObserver === "function") {
			new MutationObserver(attach).observe(document.body, { childList: true });
		} else {
			document.addEventListener("DOMContentLoaded", attach);
		}
	} catch (e) {}
})();
</script>