DEV Community

Sumit Roy
Sumit Roy

Posted on

๐ŸŽ‰ Friday Fun: Building a B-Tree Visualizer (Because We're Nerds)

It's Friday afternoon. Your brain is fried from the week. You could mindlessly scroll social media... OR you could build something cool that helps visualize those B-Trees we talked about yesterday.

Guess which one we're doing?

The Weekend Project That Actually Teaches You Something

Remember yesterday's B-Tree enlightenment? Let's build a simple visualizer to see these tree structures in action. Because sometimes the best way to understand something is to watch it work.

What We're Building

A simple web-based B-Tree visualizer that:

  • Shows how insertions affect tree structure
  • Visualizes tree balancing in real-time
  • Demonstrates why B-Trees are perfect for databases
  • Looks cool enough to show off to your colleagues

The Tech Stack (Keep It Simple)

  • HTML5 Canvas: For drawing the tree
  • Vanilla JavaScript: Because not everything needs a framework
  • CSS: To make it not look like 1995
  • Coffee: Essential for any Friday coding session

The Core Algorithm (Simplified)

class BTreeNode {
    constructor(degree) {
        this.keys = [];
        this.children = [];
        this.isLeaf = true;
        this.degree = degree; // Max keys = 2*degree - 1
    }

    insert(key) {
        // If leaf, insert and sort
        if (this.isLeaf) {
            this.keys.push(key);
            this.keys.sort((a, b) => a - b);

            // Split if too many keys
            if (this.keys.length >= 2 * this.degree) {
                return this.split();
            }
        }
        // If internal node, find right child and recurse
        else {
            let i = 0;
            while (i < this.keys.length && key > this.keys[i]) {
                i++;
            }
            return this.children[i].insert(key);
        }
    }

    split() {
        // This is where the magic happens
        // Split node and promote middle key
        const mid = Math.floor(this.keys.length / 2);
        const midKey = this.keys[mid];

        // Create new node with right half
        const newNode = new BTreeNode(this.degree);
        newNode.keys = this.keys.splice(mid + 1);

        // Current node keeps left half
        this.keys = this.keys.slice(0, mid);

        return { promotedKey: midKey, newNode: newNode };
    }
}
Enter fullscreen mode Exit fullscreen mode

The Visualization Magic

function drawTree(canvas, rootNode) {
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Start drawing from root
    drawNode(ctx, rootNode, canvas.width / 2, 50, 0);
}

function drawNode(ctx, node, x, y, level) {
    const nodeWidth = 60 * node.keys.length;
    const nodeHeight = 40;

    // Draw node rectangle
    ctx.fillStyle = level === 0 ? '#4a90e2' : '#7ed321';
    ctx.fillRect(x - nodeWidth/2, y, nodeWidth, nodeHeight);

    // Draw keys
    ctx.fillStyle = 'white';
    ctx.font = '14px Arial';
    node.keys.forEach((key, i) => {
        ctx.fillText(key, x - nodeWidth/2 + 10 + i * 50, y + 25);
    });

    // Draw children recursively
    if (!node.isLeaf) {
        const childY = y + 80;
        const childSpacing = nodeWidth / node.children.length;

        node.children.forEach((child, i) => {
            const childX = x - nodeWidth/2 + childSpacing * (i + 0.5);

            // Draw connection line
            ctx.strokeStyle = '#333';
            ctx.beginPath();
            ctx.moveTo(x - nodeWidth/2 + childSpacing * i, y + nodeHeight);
            ctx.lineTo(childX, childY);
            ctx.stroke();

            // Draw child node
            drawNode(ctx, child, childX, childY, level + 1);
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

The Interactive Part

// Add some user interaction
document.getElementById('insertBtn').addEventListener('click', () => {
    const value = parseInt(document.getElementById('keyInput').value);
    if (!isNaN(value)) {
        insertWithAnimation(value);
        document.getElementById('keyInput').value = '';
    }
});

function insertWithAnimation(key) {
    // Highlight the path the insertion takes
    animateInsertion(key).then(() => {
        tree.insert(key);
        drawTree(canvas, tree.root);
    });
}
Enter fullscreen mode Exit fullscreen mode

Why This Is Actually Useful

Building this visualizer teaches you:

  1. Tree traversal: You see exactly how searches navigate the tree
  2. Balancing behavior: Watch splits happen in real-time
  3. Performance characteristics: Count the levels as the tree grows
  4. Index design intuition: See why column order matters in compound indexes

Weekend Challenge Extensions

Once you have the basic version working:

Level 2: Add deletion (way trickier than insertion!)

Level 3: Show disk read animations (pause at each node access)

Level 4: Compare B-Tree vs Binary Tree performance

Level 5: Simulate actual database queries with range searches

The Real Payoff

Next Monday, when someone asks "Why is this query slow?", you'll be able to visualize the B-Tree traversal in your head. You'll think about:

  • How many levels the tree has
  • Whether the query can use the index structure efficiently
  • Where the disk seeks are happening

Share Your Creation

If you build this (or something similar), drop a link in the comments! Let's see different approaches to visualizing these data structures.

Bonus points if you:

  • Add sound effects for splits and searches
  • Include a "database query simulator" mode
  • Make it responsive for mobile viewing
  • Add dark mode (because it's 2025)

Weekend Motivation

Sure, you could binge Netflix this weekend. But imagine walking into Monday's standup with "Oh, I just built a B-Tree visualizer to better understand database performance."

That's the kind of weekend project that turns you from a developer who uses databases into a developer who understands databases.

What's your favorite way to learn complex concepts? Building visualizations? Reading code? Drawing diagrams? Share your learning hacks in the comments!

Next Week: We start a new Daily Doses cycle with fresh Monday motivation!


Part of the ๐ŸŒˆ Daily Dev Doses series - because the best way to understand something is to build it yourself

Top comments (0)