-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInOrderBinaryTreeTraversal.html
More file actions
492 lines (446 loc) · 15.9 KB
/
InOrderBinaryTreeTraversal.html
File metadata and controls
492 lines (446 loc) · 15.9 KB
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
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Binary Tree In-Order Traversal Visualizer</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=JetBrains+Mono&display=swap');
body {
font-family: 'Inter', sans-serif;
background-color: #f8fafc;
overflow-x: hidden;
}
.mono {
font-family: 'JetBrains Mono', monospace;
}
.node-circle {
transition: all 0.3s ease;
}
.node-active {
fill: #3b82f6;
stroke: #000000;
stroke-width: 3px;
filter: drop-shadow(0 0 8px rgba(59, 130, 246, 0.5));
}
.node-visited {
fill: #10b981;
stroke: #000000;
stroke-width: 2px;
}
.node-in-stack {
fill: #f59e0b;
stroke: #000000;
stroke-width: 2px;
}
.stack-item {
transition:
transform 0.2s ease,
opacity 0.2s ease;
}
.canvas-container {
position: relative;
overflow: hidden;
background: white;
border-radius: 12px;
box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.05);
}
/* Custom scrollbar for result container */
#resultContainer::-webkit-scrollbar {
height: 6px;
}
#resultContainer::-webkit-scrollbar-thumb {
background: #cbd5e1;
border-radius: 3px;
}
</style>
</head>
<body class="p-2 md:p-4">
<div class="max-w-7xl mx-auto space-y-4">
<!-- Compact Header & Toolbar - Fixed positions for controls -->
<header
class="flex flex-col xl:flex-row xl:items-center justify-between gap-6 bg-white p-6 rounded-xl shadow-sm border border-slate-200"
>
<div class="flex-shrink-0">
<h1 class="text-3xl font-bold text-slate-800 leading-tight">
In-Order Binary Tree Traversal
</h1>
<p class="text-lg text-slate-500">Iterative Visualisation</p>
</div>
<div class="flex flex-wrap items-center gap-6">
<!-- Settings Group - Fixed spacing -->
<div
class="flex items-center gap-6 border-r border-slate-200 pr-6 flex-shrink-0"
>
<div class="flex flex-col w-32 flex-shrink-0">
<label
class="text-sm font-bold uppercase text-slate-400 tracking-wide mb-1"
>Nodes:
<span id="nodeCountVal" class="text-blue-600">10</span></label
>
<input
type="range"
id="nodeCount"
min="3"
max="50"
value="10"
class="w-full h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-blue-600"
/>
</div>
<div class="flex flex-col flex-shrink-0">
<label
class="text-sm font-bold uppercase text-slate-400 tracking-wide mb-1"
>Balance</label
>
<select
id="treeBalance"
class="text-lg p-2 rounded border border-slate-200 bg-slate-50 outline-none focus:ring-1 focus:ring-blue-500 w-36"
>
<option value="random">Balanced</option>
<option value="left">Left Skew</option>
<option value="right">Right Skew</option>
</select>
</div>
<button
id="generateBtn"
class="flex-shrink-0 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-lg font-semibold rounded transition-colors shadow-sm"
>
New Tree
</button>
</div>
<!-- Step Group - Fixed widths for buttons and status -->
<div class="flex items-center gap-3 flex-shrink-0">
<button
id="stepBtn"
class="flex-shrink-0 w-24 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white text-lg font-bold rounded shadow-md tracking-wider"
>
STEP
</button>
<button
id="resetBtn"
class="flex-shrink-0 w-24 py-2.5 bg-slate-200 hover:bg-slate-300 text-slate-700 text-lg font-semibold rounded"
>
Reset
</button>
<!-- Status message container with fixed width to prevent shifting -->
<div
class="hidden sm:block ml-2 px-4 py-2.5 bg-slate-900 rounded text-sm mono text-blue-400 w-[450px] overflow-hidden whitespace-nowrap text-ellipsis"
id="statusText"
>
Ready to begin...
</div>
</div>
</div>
</header>
<!-- Main Content Area -->
<div class="grid grid-cols-1 xl:grid-cols-4 gap-4">
<!-- Tree Canvas (Larger) -->
<div class="xl:col-span-3">
<div class="canvas-container h-[450px] border border-slate-200">
<svg id="treeSvg" class="w-full h-full">
<g id="linksLayer"></g>
<g id="nodesLayer"></g>
</svg>
</div>
</div>
<!-- Side/Bottom Panels -->
<div class="xl:col-span-1 flex flex-col gap-4">
<!-- Stack View -->
<div
class="bg-white p-4 rounded-xl shadow-sm border border-slate-200 flex-1"
>
<h3
class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-2"
>
Recursion Stack
</h3>
<div
id="stackContainer"
class="flex flex-col-reverse gap-1 min-h-[100px] items-center border-t border-slate-50 pt-2 overflow-y-auto max-h-[300px]"
>
<span class="text-slate-300 text-xs italic">Empty</span>
</div>
</div>
<!-- Result View -->
<div
class="bg-white p-4 rounded-xl shadow-sm border border-slate-200"
>
<h3
class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-2"
>
Output Sequence
</h3>
<div
id="resultContainer"
class="flex flex-wrap gap-1.5 min-h-[60px] content-start overflow-x-auto"
>
<!-- Result items -->
</div>
</div>
</div>
</div>
<!-- Mobile Status (visible only on small screens) -->
<div
class="sm:hidden p-3 bg-slate-900 rounded-lg text-sm mono text-blue-400"
id="statusTextMobile"
>
Ready to begin...
</div>
</div>
<script>
class TreeNode {
constructor(value, id) {
this.value = value;
this.id = id;
this.left = null;
this.right = null;
this.x = 0;
this.y = 0;
this.rank = 0;
}
}
let root = null;
let nodes = [];
let stack = [];
let traversalResult = [];
let currentNode = null;
let isComplete = false;
const svg = document.getElementById('treeSvg');
const nodesLayer = document.getElementById('nodesLayer');
const linksLayer = document.getElementById('linksLayer');
const stackContainer = document.getElementById('stackContainer');
const resultContainer = document.getElementById('resultContainer');
const statusTexts = [
document.getElementById('statusText'),
document.getElementById('statusTextMobile'),
];
const nodeCountInput = document.getElementById('nodeCount');
const nodeCountVal = document.getElementById('nodeCountVal');
function setStatus(msg) {
statusTexts.forEach((el) => {
if (el) el.innerText = msg;
});
}
function generateTree() {
const count = parseInt(nodeCountInput.value);
const balance = document.getElementById('treeBalance').value;
nodes = [];
root = null;
let values = Array.from({ length: count }, (_, i) => i + 1);
if (balance === 'random') {
values.sort(() => Math.random() - 0.5);
} else if (balance === 'left') {
values.sort((a, b) => b - a);
} else if (balance === 'right') {
values.sort((a, b) => a - b);
}
values.forEach((val) => (root = insertBST(root, val)));
resetTraversal();
layoutTree();
render();
}
function insertBST(node, val) {
if (!node) {
const newNode = new TreeNode(val, nodes.length);
nodes.push(newNode);
return newNode;
}
if (val < node.value) node.left = insertBST(node.left, val);
else node.right = insertBST(node.right, val);
return node;
}
function layoutTree() {
if (!root) return;
const depth = getDepth(root);
const width = svg.clientWidth || 800;
const height = svg.clientHeight || 450;
const padding = 40;
// First pass: Calculate in-order rank to prevent overlaps
let order = 0;
let rootRank = 0;
function assignRank(node) {
if (!node) return;
assignRank(node.left);
node.rank = ++order;
if (node === root) rootRank = node.rank;
assignRank(node.right);
}
assignRank(root);
// Calculate spacing required to keep root at width/2 and stay in bounds
// Constraint 1: width/2 + (1 - rootRank) * spacing >= padding
// Constraint 2: width/2 + (totalNodes - rootRank) * spacing <= width - padding
let spacingL =
rootRank > 1 ? (width / 2 - padding) / (rootRank - 1) : Infinity;
let spacingR =
nodes.length > rootRank
? (width / 2 - padding) / (nodes.length - rootRank)
: Infinity;
// Limit max spacing so tree doesn't get too wide on small node counts
const maxIdealSpacing = 60;
const spacing = Math.min(spacingL, spacingR, maxIdealSpacing);
const verticalSpacing = height / (depth + 2);
function setCoords(node, currentDepth) {
if (!node) return;
node.x = width / 2 + (node.rank - rootRank) * spacing;
node.y = (currentDepth + 1) * verticalSpacing;
setCoords(node.left, currentDepth + 1);
setCoords(node.right, currentDepth + 1);
}
setCoords(root, 0);
}
function getDepth(node) {
if (!node) return 0;
return 1 + Math.max(getDepth(node.left), getDepth(node.right));
}
function resetTraversal() {
stack = [];
traversalResult = [];
currentNode = root;
isComplete = false;
setStatus('Initialized. Pointer at Root.');
updateUI();
}
function step() {
if (isComplete) return;
if (currentNode) {
if (currentNode.left) {
stack.push(currentNode);
setStatus(`Push ${currentNode.value} to stack and move Left.`);
currentNode = currentNode.left;
} else {
traversalResult.push(currentNode.value);
const isLeaf = !currentNode.right;
setStatus(
isLeaf
? `Leaf node ${currentNode.value} visited immediately (skipped stack).`
: `Node ${currentNode.value} has no left child. Visiting immediately and moving Right.`,
);
currentNode = currentNode.right;
}
} else {
if (stack.length > 0) {
const popped = stack.pop();
traversalResult.push(popped.value);
setStatus(
`Returned from left subtree. Popped and visited ${popped.value}. Moving Right.`,
);
currentNode = popped.right;
} else {
isComplete = true;
setStatus('Traversal Complete!');
}
}
updateUI();
}
function updateUI() {
renderNodes();
renderStack();
renderResult();
}
function renderNodes() {
nodesLayer.innerHTML = '';
linksLayer.innerHTML = '';
const count = nodes.length;
const radius = count > 30 ? 10 : count > 20 ? 12 : 16;
const fontSize = count > 30 ? '8px' : '10px';
nodes.forEach((node) => {
if (node.left) renderLink(node, node.left);
if (node.right) renderLink(node, node.right);
const g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
let stateClass = 'fill-white stroke-black stroke-2';
if (traversalResult.includes(node.value)) stateClass = 'node-visited';
else if (stack.includes(node)) stateClass = 'node-in-stack';
if (node === currentNode) stateClass = 'node-active';
const circle = document.createElementNS(
'http://www.w3.org/2000/svg',
'circle',
);
circle.setAttribute('cx', node.x);
circle.setAttribute('cy', node.y);
circle.setAttribute('r', radius);
circle.setAttribute('class', `node-circle ${stateClass}`);
const text = document.createElementNS(
'http://www.w3.org/2000/svg',
'text',
);
text.setAttribute('x', node.x);
text.setAttribute('y', node.y + radius / 4);
text.setAttribute('text-anchor', 'middle');
text.setAttribute(
'style',
`font-size: ${fontSize}; font-weight: bold; cursor: default; user-select: none;`,
);
text.setAttribute(
'class',
stateClass.includes('visited') ||
stateClass.includes('active') ||
stateClass.includes('stack')
? 'fill-white'
: 'fill-slate-500',
);
text.textContent = node.value;
g.appendChild(circle);
g.appendChild(text);
nodesLayer.appendChild(g);
});
}
function renderLink(p, c) {
const line = document.createElementNS(
'http://www.w3.org/2000/svg',
'line',
);
line.setAttribute('x1', p.x);
line.setAttribute('y1', p.y);
line.setAttribute('x2', c.x);
line.setAttribute('y2', c.y);
line.setAttribute('stroke', '#000000');
line.setAttribute('stroke-width', '1.5');
linksLayer.appendChild(line);
}
function renderStack() {
if (stack.length === 0) {
stackContainer.innerHTML =
'<span class="text-slate-300 text-xs italic">Empty</span>';
return;
}
stackContainer.innerHTML = stack
.map(
(node) => `
<div class="stack-item w-[15%] min-w-[32px] py-1.5 bg-amber-500 text-white rounded text-center font-bold text-[10px] shadow-sm border border-amber-600">
${node.value}
</div>
`,
)
.join('');
}
function renderResult() {
resultContainer.innerHTML = traversalResult
.map(
(val) => `
<div class="w-6 h-6 sm:w-8 sm:h-8 flex-shrink-0 flex items-center justify-center bg-emerald-500 text-white rounded-full font-bold text-[10px] sm:text-xs shadow-sm">
${val}
</div>
`,
)
.join('');
}
function render() {
layoutTree();
updateUI();
}
document
.getElementById('generateBtn')
.addEventListener('click', generateTree);
document.getElementById('stepBtn').addEventListener('click', step);
document
.getElementById('resetBtn')
.addEventListener('click', resetTraversal);
nodeCountInput.addEventListener('input', (e) => {
nodeCountVal.innerText = e.target.value;
});
window.addEventListener('resize', render);
window.onload = generateTree;
</script>
</body>
</html>