Prompt specification
Build or customize the Three.js 3D scene "Balanced and skewed tree comparison" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Balanced and skewed tree comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/balanced-and-skewed-tree-comparison-x1914
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows binary search trees and their balance. Insert selected key sequences into two ordinary search trees and compare resulting depths; show why the insertion order affects performance without claiming automatic balancing. Stylized solid forms.
Working Three.js Starter (balanced-and-skewed-tree-comparison-x1914):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Binary Search Trees — Insertion Order Matters</title>
<style>
:root {
color-scheme: dark;
--bg: #07111b;
--panel: #0c1925;
--panel-2: #102231;
--line: #20384a;
--text: #edf7fb;
--muted: #91a9b8;
--a: #40d9ca;
--a-dark: #168d91;
--b: #ffb45c;
--b-dark: #b86628;
--danger: #ff7c82;
--shadow: 0 18px 60px rgba(0, 0, 0, 0.28);
}
* {
box-sizing: border-box;
}
html {
scroll-behavior: smooth;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
color: var(--text);
background:
radial-gradient(circle at 12% 0%, rgba(36, 147, 154, 0.15), transparent 30rem),
radial-gradient(circle at 88% 8%, rgba(226, 132, 55, 0.12), transparent 28rem),
var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input,
select {
font: inherit;
}
button,
select {
color: var(--text);
}
button {
cursor: pointer;
}
button:focus-visible,
input:focus-visible,
select:focus-visible {
outline: 2px solid #8cecff;
outline-offset: 3px;
}
.app {
width: min(1500px, calc(100% - 32px));
margin: 0 auto;
padding: 28px 0 42px;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
margin-bottom: 22px;
}
.brand {
display: flex;
align-items: center;
gap: 14px;
}
.brand-mark {
position: relative;
width: 44px;
height: 44px;
flex: 0 0 auto;
border: 1px solid rgba(64, 217, 202, 0.45);
border-radius: 13px;
background: rgba(64, 217, 202, 0.08);
box-shadow: inset 0 0 20px rgba(64, 217, 202, 0.06);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
border-radius: 50%;
background: var(--a);
box-shadow: 0 0 14px rgba(64, 217, 202, 0.42);
}
.brand-mark::before {
width: 12px;
height: 12px;
top: 8px;
left: 8px;
}
.brand-mark::after {
width: 9px;
height: 9px;
right: 8px;
bottom: 8px;
background: var(--b);
box-shadow: 0 0 14px rgba(255, 180, 92, 0.42);
}
.eyebrow {
margin: 0 0 4px;
color: var(--a);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.45rem, 2.6vw, 2.15rem);
line-height: 1.05;
letter-spacing: -0.035em;
}
.top-note {
max-width: 470px;
margin: 0;
color: var(--muted);
font-size: 0.92rem;
line-height: 1.55;
text-align: right;
}
.top-note strong {
color: var(--text);
}
.control-deck {
display: grid;
grid-template-columns: minmax(190px, 0.8fr) minmax(230px, 1fr) auto;
gap: 16px;
align-items: end;
padding: 18px;
margin-bottom: 18px;
border: 1px solid var(--line);
border-radius: 18px;
background:
linear-gradient(135deg, rgba(255, 255, 255, 0.025), transparent),
var(--panel);
box-shadow: var(--shadow);
}
.field {
min-width: 0;
}
.field-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 0 0 8px;
color: var(--muted);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
select,
.sequence-input {
width: 100%;
min-height: 44px;
border: 1px solid #294257;
border-radius: 10px;
background: #081521;
color: var(--text);
}
select {
padding: 0 38px 0 12px;
}
.sequence-input {
padding: 10px 12px;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 0.84rem;
line-height: 1.5;
}
.sequence-input:focus {
border-color: rgba(64, 217, 202, 0.65);
}
.tree-card.invalid .sequence-input {
border-color: var(--danger);
}
.action-row {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
}
.button {
min-height: 42px;
padding: 9px 13px;
border: 1px solid #2b465a;
border-radius: 10px;
background: #102332;
color: #dbeaf1;
font-size: 0.8rem;
font-weight: 750;
transition:
transform 150ms ease,
border-color 150ms ease,
background 150ms ease;
}
.button:hover {
transform: translateY(-1px);
border-color: #41647b;
background: #162c3c;
}
.button.primary {
border-color: rgba(64, 217, 202, 0.48);
background: rgba(64, 217, 202, 0.13);
color: #b9fff8;
}
.comparison-banner {
display: grid;
grid-template-columns: auto 1fr;
gap: 14px;
align-items: start;
margin-bottom: 18px;
padding: 15px 18px;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(12, 25, 37, 0.9);
}
.comparison-badge {
align-self: center;
padding: 7px 9px;
border-radius: 7px;
background: #183043;
color: #9db8c9;
font-size: 0.65rem;
font-weight: 850;
letter-spacing: 0.12em;
white-space: nowrap;
}
.comparison-banner.warning {
border-color: rgba(255, 124, 130, 0.45);
}
.comparison-banner.warning .comparison-badge {
background: rgba(255, 124, 130, 0.12);
color: #ffafb3;
}
.comparison-title {
margin: 0 0 4px;
font-size: 0.97rem;
font-weight: 800;
}
.comparison-copy {
margin: 0;
color: var(--muted);
font-size: 0.84rem;
line-height: 1.5;
}
.tree-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 18px;
}
.tree-card {
position: relative;
overflow: hidden;
min-width: 0;
border: 1px solid var(--line);
border-radius: 20px;
background: var(--panel);
box-shadow: var(--shadow);
}
.tree-card::before {
content: "";
position: absolute;
inset: 0 0 auto;
height: 3px;
background: var(--accent);
}
.tree-card[data-side="a"] {
--accent: var(--a);
--accent-soft: rgba(64, 217, 202, 0.12);
}
.tree-card[data-side="b"] {
--accent: var(--b);
--accent-soft: rgba(255, 180, 92, 0.12);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 17px 18px 12px;
}
.tree-heading {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
}
.tree-letter {
display: grid;
width: 34px;
height: 34px;
flex: 0 0 auto;
place-items: center;
border-radius: 10px;
background: var(--accent-soft);
color: var(--accent);
font-weight: 900;
}
.tree-heading h2 {
margin: 0;
font-size: 1rem;
letter-spacing: -0.015em;
}
.tree-heading p {
margin: 3px 0 0;
color: var(--muted);
font-size: 0.73rem;
}
.tree-tags {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 6px;
}
.tag {
padding: 5px 7px;
border: 1px solid #284155;
border-radius: 999px;
color: #a9c0ce;
font-size: 0.65rem;
font-weight: 800;
letter-spacing: 0.05em;
text-transform: uppercase;
white-space: nowrap;
}
.tag.root {
border-color: color-mix(in srgb, var(--accent), transparent 55%);
color: var(--accent);
}
.editor {
padding: 0 18px 14px;
}
.editor-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
}
.editor-top label {
color: #c7d9e3;
font-size: 0.74rem;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.quick-orders {
display: flex;
flex-wrap: wrap;
gap: 5px;
}
.quick-orders button {
padding: 4px 7px;
border: 1px solid #294357;
border-radius: 7px;
background: transparent;
color: #91adbd;
font-size: 0.67rem;
font-weight: 750;
}
.quick-orders button:hover {
border-color: var(--accent);
color: var(--accent);
}
.input-error {
min-height: 16px;
margin: 5px 0 0;
color: var(--danger);
font-size: 0.7rem;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 5px;
min-height: 31px;
margin-top: 7px;
}
.chip {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 4px 7px 4px 4px;
border: 1px solid #284155;
border-radius: 7px;
background: #0a1722;
color: #d7e7ef;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 0.72rem;
}
.chip i {
display: grid;
width: 17px;
height: 17px;
place-items: center;
border-radius: 4px;
background: var(--accent-soft);
color: var(--accent);
font-family: inherit;
font-size: 0.58rem;
font-style: normal;
font-weight: 800;
}
.viewport {
position: relative;
height: 360px;
overflow: hidden;
border-top: 1px solid rgba(40, 65, 85, 0.65);
border-bottom: 1px solid rgba(40, 65, 85, 0.65);
background: #0a1722;
touch-action: none;
}
.viewport > canvas {
position: absolute;
inset: 0;
z-index: 0;
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
.viewport > canvas:active {
cursor: grabbing;
}
.camera-hint {
position: absolute;
left: 12px;
bottom: 11px;
z-index: 3;
padding: 6px 8px;
border: 1px solid rgba(93, 124, 143, 0.34);
border-radius: 7px;
background: rgba(5, 14, 22, 0.7);
color: #8ca6b6;
font-size: 0.65rem;
pointer-events: none;
backdrop-filter: blur(6px);
}
.reset-camera {
position: absolute;
top: 11px;
right: 11px;
z-index: 4;
min-height: 28px;
padding: 5px 8px;
border: 1px solid rgba(93, 124, 143, 0.35);
border-radius: 7px;
background: rgba(5, 14, 22, 0.72);
color: #9db4c2;
font-size: 0.65rem;
font-weight: 750;
}
.reset-camera:hover {
color: var(--accent);
border-color: var(--accent);
}
.metrics {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
padding: 14px 18px 10px;
}
.metric {
min-width: 0;
padding: 10px;
border: 1px solid #20394b;
border-radius: 10px;
background: #091722;
}
.metric-label {
display: block;
margin-bottom: 5px;
color: #819aaa;
font-size: 0.61rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
white-space: nowrap;
}
.metric-value {
display: block;
overflow: hidden;
color: var(--text);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 1.02rem;
font-weight: 800;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric-value.accent {
color: var(--accent);
}
.depth-bar {
height: 4px;
margin-top: 8px;
overflow: hidden;
border-radius: 999px;
background: #172b3a;
}
.depth-bar span {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: var(--accent);
transition: width 350ms ease;
}
.metric-foot {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 0 18px 16px;
color: #738d9d;
font-size: 0.67rem;
line-height: 1.4;
}
.explanation {
display: grid;
grid-template-columns: 1.1fr 1fr 1fr;
gap: 12px;
margin-top: 18px;
}
.explain-card {
padding: 16px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(12, 25, 37, 0.78);
}
.explain-card h3 {
margin: 0 0 7px;
font-size: 0.84rem;
}
.explain-card p {
margin: 0;
color: var(--muted);
font-size: 0.76rem;
line-height: 1.55;
}
.explain-card strong {
color: #d8e8ef;
}
.footer {
display: flex;
justify-content: space-between;
gap: 18px;
margin-top: 18px;
padding: 0 3px;
color: #6f8999;
font-size: 0.7rem;
line-height: 1.5;
}
.footer code {
color: #9ab2c0;
}
@media (max-width: 1000px) {
.control-deck {
grid-template-columns: 1fr 1fr;
}
.action-row {
grid-column: 1 / -1;
justify-content: flex-start;
}
.tree-grid {
grid-template-columns: 1fr;
}
.viewport {
height: 410px;
}
}
@media (max-width: 650px) {
.app {
width: min(100% - 20px, 1500px);
padding-top: 18px;
}
.topbar {
align-items: flex-start;
}
.top-note {
display: none;
}
.control-deck {
grid-template-columns: 1fr;
}
.action-row {
grid-column: auto;
}
.comparison-banner {
grid-template-columns: 1fr;
}
.comparison-badge {
justify-self: start;
}
.card-header {
align-items: flex-start;
}
.tree-tags {
max-width: 145px;
}
.editor-top {
align-items: flex-start;
flex-direction: column;
}
.metrics {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.viewport {
height: 350px;
}
.explanation {
grid-template-columns: 1fr;
}
.footer {
flex-direction: column;
}
}
</style>
</head>
<body>
<main class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<p class="eyebrow">Data Structures / Visual Lab</p>
<h1>Same keys. Different depth.</h1>
</div>
</div>
<p class="top-note">
A binary search tree stores keys in a strict left/right order, but an
<strong>ordinary BST does not rotate or rebalance itself</strong>.
Insertion order changes the shape it creates.
</p>
</header>
<section class="control-deck" aria-label="Tree controls">
<div class="field">
<label class="field-label" for="keyset">Shared key set</label>
<select id="keyset">
<option value="nine">1–9 · classic set</option>
<option value="fifteen">1–15 · wider set</option>
<option value="mixed">Mixed values · 42, 18, 73…</option>
</select>
</div>
<div class="field">
<label class="field-label" for="recipe">Comparison recipe</label>
<select id="recipe">
<option value="balanced-asc">Center-out vs. ascending</option>
<option value="asc-desc">Ascending vs. descending</option>
<option value="balanced-desc">Center-out vs. descending</option>
<option value="same">Same insertion order</option>
<option value="random">Two shuffled orders</option>
</select>
</div>
<div class="action-row">
<button class="button" id="shuffleButton" type="button">Shuffle pair</button>
<button class="button" id="swapButton" type="button">Swap orders</button>
<button class="button primary" id="replayButton" type="button">Replay inserts</button>
</div>
</section>
<section class="comparison-banner" id="comparisonBanner" aria-live="polite">
<div class="comparison-badge" id="comparisonBadge">Controlled comparison</div>
<div>
<p class="comparison-title" id="comparisonTitle">Building the trees…</p>
<p class="comparison-copy" id="comparisonCopy"></p>
</div>
</section>
<section class="tree-grid">
<article class="tree-card" id="cardA" data-side="a">
<header class="card-header">
<div class="tree-heading">
<div class="tree-letter">A</div>
<div>
<h2>Tree A</h2>
<p>First insertion becomes the root</p>
</div>
</div>
<div class="tree-tags">
<span class="tag root" id="rootA">Root —</span>
<span class="tag" id="countA">0 unique</span>
</div>
</header>
<div class="editor">
<div class="editor-top">
<label for="sequenceA">Insertion sequence</label>
<div class="quick-orders">
<button type="button" data-side="a" data-order="balanced">Center-out</button>
<button type="button" data-side="a" data-order="ascending">Ascending</button>
<button type="button" data-side="a" data-order="descending">Descending</button>
</div>
</div>
<input
class="sequence-input"
id="sequenceA"
type="text"
inputmode="decimal"
autocomplete="off"
spellcheck="false"
aria-describedby="errorA"
/>
<p class="input-error" id="errorA"></p>
<div class="chips" id="chipsA" aria-label="Tree A insertion order"></div>
</div>
<div class="viewport" id="viewA">
<div class="camera-hint">Drag to orbit · scroll to zoom</div>
<button class="reset-camera" type="button" data-reset="a">Reset view</button>
</div>
<div class="metrics">
<div class="metric">
<span class="metric-label">Avg. depth</span>
<span class="metric-value accent" id="avgA">—</span>
<div class="depth-bar"><span id="avgBarA"></span></div>
</div>
<div class="metric">
<span class="metric-label">Max depth</span>
<span class="metric-value" id="maxA">—</span>
</div>
<div class="metric">
<span class="metric-label">Height</span>
<span class="metric-value" id="heightA">—</span>
</div>
<div class="metric" title="Range of local balance factors: left subtree height minus right subtree height.">
<span class="metric-label">Local BF range</span>
<span class="metric-value" id="bfA">—</span>
</div>
</div>
<div class="metric-foot">
<span>Depth is measured in edges from the root.</span>
<span id="shapeA">—</span>
</div>
</article>
<article class="tree-card" id="cardB" data-side="b">
<header class="card-header">
<div class="tree-heading">
<div class="tree-letter">B</div>
<div>
<h2>Tree B</h2>
<p>Only the insertion order changes</p>
</div>
</div>
<div class="tree-tags">
<span class="tag root" id="rootB">Root —</span>
<span class="tag" id="countB">0 unique</span>
</div>
</header>
<div class="editor">
<div class="editor-top">
<label for="sequenceB">Insertion sequence</label>
<div class="quick-orders">
<button type="button" data-side="b" data-order="balanced">Center-out</button>
<button type="button" data-side="b" data-order="ascending">Ascending</button>
<button type="button" data-side="b" data-order="descending">Descending</button>
</div>
</div>
<input
class="sequence-input"
id="sequenceB"
type="text"
inputmode="decimal"
autocomplete="off"
spellcheck="false"
aria-describedby="errorB"
/>
<p class="input-error" id="errorB"></p>
<div class="chips" id="chipsB" aria-label="Tree B insertion order"></div>
</div>
<div class="viewport" id="viewB">
<div class="camera-hint">Drag to orbit · scroll to zoom</div>
<button class="reset-camera" type="button" data-reset="b">Reset view</button>
</div>
<div class="metrics">
<div class="metric">
<span class="metric-label">Avg. depth</span>
<span class="metric-value accent" id="avgB">—</span>
<div class="depth-bar"><span id="avgBarB"></span></div>
</div>
<div class="metric">
<span class="metric-label">Max depth</span>
<span class="metric-value" id="maxB">—</span>
</div>
<div class="metric">
<span class="metric-label">Height</span>
<span class="metric-value" id="heightB">—</span>
</div>
<div class="metric" title="Range of local balance factors: left subtree height minus right subtree height.">
<span class="metric-label">Local BF range</span>
<span class="metric-value" id="bfB">—</span>
</div>
</div>
<div class="metric-foot">
<span>BF = left subtree height − right subtree height.</span>
<span id="shapeB">—</span>
</div>
</article>
</section>
<section class="explanation" aria-label="Explanation">
<article class="explain-card">
<h3>1 · Insert by comparison</h3>
<p>
The first key is the root. Each later key walks left when it is smaller,
right when it is larger, and occupies the first empty position on that path.
Duplicates are ignored in this ordinary BST.
</p>
</article>
<article class="explain-card">
<h3>2 · The first choice cascades</h3>
<p>
A poor early root can split the remaining keys into one long side.
A later key then travels through every earlier ancestor before finding
its position, increasing the tree's path lengths.
</p>
</article>
<article class="explain-card">
<h3>3 · No automatic balancing</h3>
<p>
These are plain BSTs: there are <strong>no AVL or Red-Black rotations</strong>.
The shallow tree is shallow because of its insertion order, not because
the data structure repaired itself.
</p>
</article>
</section>
<footer class="footer">
<span>
Ordinary BST worst case: <code>O(n)</code> depth. A favorable insertion order
can produce a much shallower tree, but does not guarantee balance.
</span>
<span>Three.js core only · custom orbit and zoom controls</span>
</footer>
</main>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const KEY_SETS = {
nine: Array.from({ length: 9 }, (_, i) => i + 1),
fifteen: Array.from({ length: 15 }, (_, i) => i + 1),
mixed: [42, 18, 73, 7, 26, 55, 88, 12, 21, 34, 48, 63, 91, 31, 77]
};
const ACCENTS = {
a: 0x40d9ca,
b: 0xffb45c
};
const state = {
a: [],
b: []
};
const dom = {
keyset: document.querySelector("#keyset"),
recipe: document.querySelector("#recipe"),
comparisonBanner: document.querySelector("#comparisonBanner"),
comparisonBadge: document.querySelector("#comparisonBadge"),
comparisonTitle: document.querySelector("#comparisonTitle"),
comparisonCopy: document.querySelector("#comparisonCopy")
};
function formatKey(value) {
if (Number.isInteger(value)) return String(value);
return Number(value.toFixed(3)).toString();
}
function formatNumber(value) {
if (!Number.isFinite(value)) return "—";
return Number(value.toFixed(2)).toString();
}
function sortedKeys() {
return [...KEY_SETS[dom.keyset.value]].sort((a, b) => a - b);
}
function balancedInsertionOrder(values) {
const sorted = [...values].sort((a, b) => a - b);
const result = [];
function visit(list) {
if (!list.length) return;
const middle = Math.floor(list.length / 2);
result.push(list[middle]);
visit(list.slice(0, middle));
visit(list.slice(middle + 1));
}
visit(sorted);
return result;
}
function shuffled(values) {
const result = [...values];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
function parseSequence(text) {
const source = text.trim();
if (!source) {
return { error: "Enter at least one numeric key." };
}
const tokens = source.split(/[\s,]+/).filter(Boolean);
const values = [];
const invalid = [];
for (const token of tokens) {
const value = Number(token);
if (!Number.isFinite(value)) {
invalid.push(token);
} else {
values.push(value);
}
}
if (invalid.length) {
return { error: `Not numeric: ${invalid.join(", ")}` };
}
return { values };
}
function insertSequence(sequence) {
let root = null;
let ignoredDuplicates = 0;
for (const key of sequence) {
if (!root) {
root = { key, left: null, right: null, depth: 0, insertionIndex: 0 };
continue;
}
let current = root;
let depth = 0;
while (true) {
depth++;
if (key === current.key) {
ignoredDuplicates++;
break;
}
if (key < current.key) {
if (!current.left) {
current.left = {
key,
left: null,
right: null,
depth,
insertionIndex: sequence.indexOf(key)
};
break;
}
current = current.left;
} else {
if (!current.right) {
current.right = {
key,
left: null,
right: null,
depth,
insertionIndex: sequence.indexOf(key)
};
break;
}
current = current.right;
}
}
}
return { root, ignoredDuplicates };
}
function measureTree(node) {
if (!node) {
return {
height: -1,
count: 0,
minBalance: Infinity,
maxBalance: -Infinity
};
}
const left = measureTree(node.left);
const right = measureTree(node.right);
const balance = left.height - right.height;
return {
height: 1 + Math.max(left.height, right.height),
count: 1 + left.count + right.count,
minBalance: Math.min(left.minBalance, right.minBalance, balance),
maxBalance: Math.max(left.maxBalance, right.maxBalance, balance)
};
}
function calculateStats(root, sequence, ignoredDuplicates) {
let sumDepth = 0;
let maxDepth = 0;
let nodeCount = 0;
function visit(node) {
if (!node) return;
nodeCount++;
sumDepth += node.depth;
maxDepth = Math.max(maxDepth, node.depth);
visit(node.left);
visit(node.right);
}
visit(root);
const measured = measureTree(root);
return {
root,
nodeCount,
uniqueCount: new Set(sequence).size,
ignoredDuplicates,
averageDepth: nodeCount ? sumDepth / nodeCount : 0,
maxDepth,
height: nodeCount ? maxDepth + 1 : 0,
minBalance: measured.minBalance,
maxBalance: measured.maxBalance
};
}
function createLabelSprite(key, accent) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const context = canvas.getContext("2d");
const color = new THREE.Color(accent).getStyle();
context.clearRect(0, 0, 128, 128);
context.beginPath();
context.arc(64, 64, 47, 0, Math.PI * 2);
context.fillStyle = "rgba(6, 17, 27, 0.94)";
context.fill();
context.lineWidth = 5;
context.strokeStyle = color;
context.stroke();
context.fillStyle = "#f3fbff";
context.font = "800 48px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(formatKey(key), 64, 66);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.52, 0.52, 0.52);
sprite.position.set(0, 0.47, 0);
sprite.renderOrder = 20;
return sprite;
}
class TreeView {
constructor(container, side) {
this.container = container;
this.side = side;
this.accent = ACCENTS[side];
this.sequence = [];
this.stats = null;
this.nodes = [];
this.branches = [];
this.buildStarted = 0;
this.reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
this.yaw = -0.08;
this.pitch = 0.18;
this.zoom = 1;
this.target = new THREE.Vector3(0, 0, 0);
this.treeWidth = 8;
this.treeHeight = 7;
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.18;
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
this.renderer.domElement.setAttribute(
"aria-label",
`Interactive 3D binary search tree ${side.toUpperCase()}`
);
this.container.prepend(this.renderer.domElement);
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(
side === "a" ? 0x091923 : 0x191923
);
this.camera = new THREE.OrthographicCamera(-5, 5, 5, -5, 0.1, 100);
this.group = new THREE.Group();
this.scene.add(this.group);
const hemisphere = new THREE.HemisphereLight(0xd9f5ff, 0x07111b, 2.2);
this.scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(4, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 15;
keyLight.shadow.camera.bottom = -15;
keyLight.shadow.bias = -0.0015;
this.scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(
side === "a" ? 0x41e8df : 0xffa84d,
1.55
);
rimLight.position.set(-6, 4, -5);
this.scene.add(rimLight);
this.bindCameraControls();
this.resizeObserver = new ResizeObserver(() => this.resize());
this.resizeObserver.observe(this.container);
this.resize();
}
bindCameraControls() {
const canvas = this.renderer.domElement;
let dragging = false;
let pointerId = null;
let lastX = 0;
let lastY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerId = event.pointerId;
lastX = event.clientX;
lastY = event.clientY;
canvas.setPointerCapture(pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging || event.pointerId !== pointerId) return;
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
lastX = event.clientX;
lastY = event.clientY;
this.yaw -= dx * 0.006;
this.pitch = THREE.MathUtils.clamp(this.pitch + dy * 0.0045, -0.18, 0.78);
});
const stopDragging = (event) => {
if (!dragging) return;
dragging = false;
if (pointerId !== null && canvas.hasPointerCapture(pointerId)) {
canvas.releasePointerCapture(pointerId);
}
pointerId = null;
};
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
const factor = Math.exp(-event.deltaY * 0.001);
this.zoom = THREE.MathUtils.clamp(this.zoom * factor, 0.62, 2.25);
this.updateProjection();
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => this.resetCamera());
}
resetCamera() {
this.yaw = -0.08;
this.pitch = 0.18;
this.zoom = 1;
this.updateProjection();
}
resize() {
const width = Math.max(1, this.container.clientWidth);
const height = Math.max(1, this.container.clientHeight);
this.renderer.setSize(width, height, false);
this.aspect = width / height;
this.updateProjection();
}
updateProjection() {
const aspect = this.aspect || 1;
const halfHeight =
Math.max(this.treeHeight / 2, this.treeWidth / (2 * aspect)) * 1.08;
this.camera.left = -halfHeight * aspect;
this.camera.right = halfHeight * aspect;
this.camera.top = halfHeight;
this.camera.bottom = -halfHeight;
this.camera.zoom = this.zoom;
this.camera.updateProjectionMatrix();
}
updateCamera() {
const radius = 28;
const horizontal = radius * Math.cos(this.pitch);
this.camera.position.set(
this.target.x + Math.sin(this.yaw) * horizontal,
this.target.y + Math.sin(this.pitch) * radius,
this.target.z + Math.cos(this.yaw) * horizontal
);
this.camera.lookAt(this.target);
}
clearGroup() {
const geometries = new Set();
const materials = new Set();
const textures = new Set();
this.group.traverse((object) => {
if (object.geometry) geometries.add(object.geometry);
const objectMaterials = Array.isArray(object.material)
? object.material
: object.material
? [object.material]
: [];
for (const material of objectMaterials) {
materials.add(material);
if (material.map) textures.add(material.map);
}
});
for (const geometry of geometries) geometry.dispose();
for (const material of materials) material.dispose();
for (const texture of textures) texture.dispose();
this.group.clear();
this.nodes = [];
this.branches = [];
}
build(sequence) {
this.sequence = [...sequence];
this.clearGroup();
const result = insertSequence(this.sequence);
this.stats = calculateStats(
result.root,
this.sequence,
result.ignoredDuplicates
);
if (!result.root) {
this.target.set(0, 0, 0);
this.treeWidth = 8;
this.treeHeight = 7;
this.updateProjection();
return;
}
const spacing = 0.9;
const verticalStep = 1.45;
const topY = 2.55;
const nodeCount = this.stats.nodeCount;
let inorderIndex = 0;
function positionNodes(node) {
if (!node) return;
positionNodes(node.left);
node.x = (inorderIndex - (nodeCount - 1) / 2) * spacing;
node.y = topY - node.depth * verticalStep;
inorderIndex++;
positionNodes(node.right);
}
positionNodes(result.root);
const maxDepth = this.stats.maxDepth;
const bottomY = topY - maxDepth * verticalStep;
this.treeWidth = Math.max(6.5, (this.stats.nodeCount - 1) * spacing + 2.2);
this.treeHeight = maxDepth * verticalStep + 4.1;
this.target.set(0, (topY + bottomY) / 2, 0);
this.updateProjection();
const baseRadius = this.treeWidth * 0.55;
const ground = new THREE.Mesh(
new THREE.CircleGeometry(baseRadius * 1.16, 64),
new THREE.MeshStandardMaterial({
color: this.side === "a" ? 0x102c34 : 0x33271f,
roughness: 0.94,
metalness: 0.02,
transparent: true,
opacity: 0.78
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = bottomY - 0.86;
ground.receiveShadow = true;
this.group.add(ground);
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(baseRadius, baseRadius * 0.94, 0.18, 64),
new THREE.MeshStandardMaterial({
color: this.side === "a" ? 0x173b42 : 0x493426,
roughness: 0.62,
metalness: 0.12
})
);
pedestal.position.y = bottomY - 0.72;
pedestal.castShadow = true;
pedestal.receiveShadow = true;
this.group.add(pedestal);
const parentMap = new Map();
const addNodes = (node, parent = null) => {
if (!node) return;
const depthRatio = maxDepth ? node.depth / maxDepth : 0;
const nodeColor = new THREE.Color(this.accent);
nodeColor.lerp(new THREE.Color(0xffffff), 0.28 * (1 - depthRatio));
nodeColor.multiplyScalar(1 - depthRatio * 0.12);
const group = new THREE.Group();
group.position.set(node.x, node.y, 0);
const sphere = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.29, 3),
new THREE.MeshStandardMaterial({
color: nodeColor,
roughness: 0.3,
metalness: 0.08,
emissive: new THREE.Color(this.accent).multiplyScalar(0.055)
})
);
sphere.castShadow = true;
sphere.receiveShadow = true;
group.add(sphere);
const highlight = new THREE.Mesh(
new THREE.SphereGeometry(0.075, 16, 12),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.35,
metalness: 0,
transparent: true,
opacity: 0.62
})
);
highlight.position.set(-0.095, 0.105, 0.245);
group.add(highlight);
group.add(createLabelSprite(node.key, this.accent));
this.group.add(group);
this.nodes.push({
group,
insertionIndex: node.insertionIndex
});
if (parent) parentMap.set(node, parent);
addNodes(node.left, node);
addNodes(node.right, node);
};
addNodes(result.root);
const branchColor = new THREE.Color(this.accent).multiplyScalar(0.58);
const addBranches = (node) => {
if (!node) return;
for (const child of [node.left, node.right]) {
if (!child) continue;
const start = new THREE.Vector3(node.x, node.y, 0);
const end = new THREE.Vector3(child.x, child.y, 0);
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const midpoint = new THREE.Vector3()
.addVectors(start, end)
.multiplyScalar(0.5);
const geometry = new THREE.CylinderGeometry(
0.075,
0.095,
length,
12
);
const material = new THREE.MeshStandardMaterial({
color: branchColor,
roughness: 0.58,
metalness: 0.05,
transparent: true,
opacity: 1,
depthWrite: false
});
const branch = new THREE.Mesh(geometry, material);
branch.position.copy(midpoint);
branch.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.clone().normalize()
);
branch.castShadow = true;
this.group.add(branch);
this.branches.push({
mesh: branch,
insertionIndex: child.insertionIndex
});
addBranches(child);
}
};
addBranches(result.root);
this.buildStarted = performance.now();
this.updateCamera();
}
animate(now) {
const elapsed = this.reducedMotion
? 100
: (now - this.buildStarted) / 1000;
for (const node of this.nodes) {
const t = THREE.MathUtils.clamp(
(elapsed - node.insertionIndex * 0.145) / 0.32,
0,
1
);
const eased = 1 - Math.pow(1 - t, 3);
node.group.scale.setScalar(Math.max(0.001, eased));
}
for (const branch of this.branches) {
const t = THREE.MathUtils.clamp(
(elapsed - branch.insertionIndex * 0.145) / 0.28,
0,
1
);
branch.mesh.material.opacity = t;
branch.mesh.visible = t > 0.001;
}
this.updateCamera();
this.renderer.render(this.scene, this.camera);
}
}
const views = {
a: new TreeView(document.querySelector("#viewA"), "a"),
b: new TreeView(document.querySelector("#viewB"), "b")
};
function renderChips(side, sequence) {
const target = document.querySelector(`#chips${side.toUpperCase()}`);
target.innerHTML = sequence
.map(
(key, index) =>
`<span class="chip"><i>${index + 1}</i>${formatKey(key)}</span>`
)
.join("");
}
function renderStats(side) {
const view = views[side];
const stats = view.stats;
const upper = side.toUpperCase();
if (!stats) return;
document.querySelector(`#root${upper}`).textContent =
`Root ${formatKey(stats.root.key)}`;
document.querySelector(`#count${upper}`).textContent =
`${stats.uniqueCount} unique${stats.ignoredDuplicates ? ` · ${stats.ignoredDuplicates} dup` : ""}`;
document.querySelector(`#avg${upper}`).textContent =
`${formatNumber(stats.averageDepth)} edges`;
document.querySelector(`#max${upper}`).textContent =
`${stats.maxDepth} edges`;
document.querySelector(`#height${upper}`).textContent =
`${stats.height} nodes`;
const minBF = Number.isFinite(stats.minBalance) ? stats.minBalance : 0;
const maxBF = Number.isFinite(stats.maxBalance) ? stats.maxBalance : 0;
document.querySelector(`#bf${upper}`).textContent =
minBF === maxBF
? `${minBF > 0 ? "+" : ""}${minBF}`
: `${minBF > 0 ? "+" : ""}${minBF} … ${maxBF > 0 ? "+" : ""}${maxBF}`;
const shape = document.querySelector(`#shape${upper}`);
if (stats.nodeCount > 1 && stats.maxDepth === stats.nodeCount - 1) {
shape.textContent = "Chain-like shape";
} else if (stats.averageDepth <= 2.2) {
shape.textContent = "Shallow shape";
} else if (stats.averageDepth <= 3.7) {
shape.textContent = "Moderate shape";
} else {
shape.textContent = "Deep shape";
}
}
function sameKeySet(a, b) {
const setA = new Set(a);
const setB = new Set(b);
if (setA.size !== setB.size) return false;
for (const key of setA) {
if (!setB.has(key)) return false;
}
return true;
}
function updateComparison() {
const a = views.a.stats;
const b = views.b.stats;
if (!a || !b) return;
const maximumAverage = Math.max(a.averageDepth, b.averageDepth, 1);
document.querySelector("#avgBarA").style.width =
`${(a.averageDepth / maximumAverage) * 100}%`;
document.querySelector("#avgBarB").style.width =
`${(b.averageDepth / maximumAverage) * 100}%`;
const controlled = sameKeySet(state.a, state.b);
if (!controlled) {
dom.comparisonBanner.classList.add("warning");
dom.comparisonBadge.textContent = "Different key sets";
dom.comparisonTitle.textContent = "This is no longer a controlled comparison.";
dom.comparisonCopy.textContent =
"The two sequences do not contain the same unique keys, so their average depths cannot be compared as an insertion-order experiment.";
return;
}
dom.comparisonBanner.classList.remove("warning");
dom.comparisonBadge.textContent = "Controlled comparison";
const averageDifference = b.averageDepth - a.averageDepth;
const maximumDifference = b.maxDepth - a.maxDepth;
if (Math.abs(averageDifference) < 0.01) {
dom.comparisonTitle.textContent = "The two insertion orders produced the same depth profile.";
dom.comparisonCopy.textContent =
`Both trees store ${a.uniqueCount} unique keys with an average depth of ${formatNumber(a.averageDepth)} edges and a maximum depth of ${a.maxDepth}.`;
return;
}
const shallower = averageDifference > 0 ? "A" : "B";
const deeper = averageDifference > 0 ? "B" : "A";
const difference = Math.abs(averageDifference);
const shallowerStats = shallower === "A" ? a : b;
const deeperStats = deeper === "A" ? a : b;
const percent = deeperStats.averageDepth
? (difference / deeperStats.averageDepth) * 100
: 0;
dom.comparisonTitle.textContent =
`Tree ${shallower} is shallower by ${formatNumber(difference)} average depth levels.`;
dom.comparisonCopy.textContent =
`With the same ${a.uniqueCount} keys, Tree ${shallower} averages ${formatNumber(shallowerStats.averageDepth)} edges and Tree ${deeper} averages ${formatNumber(deeperStats.averageDepth)} — a ${formatNumber(percent)}% difference. ` +
`Maximum depths are ${shallowerStats.maxDepth} and ${deeperStats.maxDepth} edges respectively. ` +
`The trees differ only because the insertion order changed; neither tree rebalanced itself.`;
}
function refresh(side) {
renderStats(side);
updateComparison();
}
function applySide(side, values) {
state[side] = [...values];
renderChips(side, state[side]);
views[side].build(state[side]);
refresh(side);
}
function setInputValue(side, values) {
const input = document.querySelector(`#sequence${side.toUpperCase()}`);
input.value = values.join(", ");
input.closest(".tree-card").classList.remove("invalid");
document.querySelector(`#error${side.toUpperCase()}`).textContent = "";
}
function regeneratePair() {
const base = sortedKeys();
const balanced = balancedInsertionOrder(base);
const ascending = [...base].sort((a, b) => a - b);
const descending = [...ascending].reverse();
let first;
let second;
switch (dom.recipe.value) {
case "asc-desc":
first = ascending;
second = descending;
break;
case "balanced-desc":
first = balanced;
second = descending;
break;
case "same":
first = balanced;
second = [...balanced];
break;
case "random":
first = shuffled(base);
second = shuffled(base);
if (first.join(",") === second.join(",")) second.reverse();
break;
case "balanced-asc":
default:
first = balanced;
second = ascending;
break;
}
setInputValue("a", first);
setInputValue("b", second);
applySide("a", first);
applySide("b", second);
}
for (const side of ["a", "b"]) {
const input = document.querySelector(`#sequence${side.toUpperCase()}`);
let timer;
input.addEventListener("input", () => {
clearTimeout(timer);
timer = setTimeout(() => {
const parsed = parseSequence(input.value);
const card = input.closest(".tree-card");
const error = document.querySelector(`#error${side.toUpperCase()}`);
if (parsed.error) {
card.classList.add("invalid");
error.textContent = parsed.error;
return;
}
card.classList.remove("invalid");
error.textContent = "";
applySide(side, parsed.values);
}, 220);
});
}
document.querySelectorAll(".quick-orders button").forEach((button) => {
button.addEventListener("click", () => {
const side = button.dataset.side;
const base = sortedKeys();
let values;
if (button.dataset.order === "balanced") {
values = balancedInsertionOrder(base);
} else if (button.dataset.order === "descending") {
values = [...base].sort((a, b) => b - a);
} else {
values = [...base].sort((a, b) => a - b);
}
setInputValue(side, values);
applySide(side, values);
});
});
document.querySelectorAll("[data-reset]").forEach((button) => {
button.addEventListener("click", () => {
views[button.dataset.reset].resetCamera();
});
});
dom.keyset.addEventListener("change", regeneratePair);
dom.recipe.addEventListener("change", regeneratePair);
document.querySelector("#swapButton").addEventListener("click", () => {
const oldA = state.a;
state.a = state.b;
state.b = oldA;
setInputValue("a", state.a);
setInputValue("b", state.b);
applySide("a", state.a);
applySide("b", state.b);
});
document.querySelector("#shuffleButton").addEventListener("click", () => {
const base = sortedKeys();
let first = shuffled(base);
let second = shuffled(base);
if (first.join(",") === second.join(",")) {
second = shuffled(base);
}
setInputValue("a", first);
setInputValue("b", second);
applySide("a", first);
applySide("b", second);
});
document.querySelector("#replayButton").addEventListener("click", () => {
views.a.build(state.a);
views.b.build(state.b);
refresh("a");
refresh("b");
});
rendererLoop();
function rendererLoop() {
const now = performance.now();
views.a.animate(now);
views.b.animate(now);
requestAnimationFrame(rendererLoop);
}
regeneratePair();
</script>
</body>
</html>
```