Skip to main content

Command Palette

Search for a command to run...

Understanding Binary Search Trees

Published
3 min read
Understanding Binary Search Trees
M

I am a backend developer, interested in writing about backend engineering, DevOps and tooling.

Introduction

Ever felt overwhelmed by data structures and algorithms? You're not alone. As a developer, understanding complex concepts like tree algorithms can feel like trying to navigate a dense forest. But fear not—you're about to get a clear path through the woods. In this article, you'll learn about Binary Search Trees (BSTs), a fundamental tree structure that offers efficient data storage and retrieval. By the end of this guide, you'll not only understand how BSTs work but also know how to implement one from scratch.

What Is a Binary Search Tree?

A Binary Search Tree is a node-based data structure where each node has at most two children, referred to as the left child and the right child. The tree maintains a specific property: for every node, all values in its left subtree are less, and all values in its right subtree are greater. This property enables fast lookup, insertion, and deletion operations.

Why Should You Use a Binary Search Tree?

Imagine needing to quickly find a specific book in a library. If the books were arranged in a random order, it would take forever. A BST acts like an organised library, where books (data) are sorted, making searches swift and efficient. This organisation allows for average-case complexities of O(log n) for insertion, deletion, and lookup operations, making BSTs highly efficient for large datasets.

Implementing a Binary Search Tree

Let's dive into the code. Below is a basic implementation of a BST in JavaScript:

class Node {
    constructor(value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

class BinarySearchTree {
    constructor() {
        this.root = null;
    }

    insert(value) {
        const newNode = new Node(value);
        if (this.root === null) {
            this.root = newNode;
        } else {
            let currentNode = this.root;
            while (true) {
                if (value < currentNode.value) {
                    if (!currentNode.left) {
                        currentNode.left = newNode;
                        return this;
                    }
                    currentNode = currentNode.left;
                } else if (value > currentNode.value) {
                    if (!currentNode.right) {
                        currentNode.right = newNode;
                        return this;
                    }
                    currentNode = currentNode.right;
                }
            }
        }
    }

    lookUp(value) {
        if (!this.root) {
            return null;
        }
        let currentNode = this.root;
        while (currentNode) {
            if (value < currentNode.value) {
                currentNode = currentNode.left;
            } else if (value > currentNode.value) {
                currentNode = currentNode.right;
            } else if (value === currentNode.value) {
                return currentNode;
            }
        }
        return null;
    }
}

const tree = new BinarySearchTree();
tree.insert(9);
tree.insert(4);
tree.insert(6);
tree.insert(20);
tree.insert(170);
tree.insert(15);
tree.insert(1);
console.log(tree.lookUp(170));

Code Breakdown

  • Node Class: Represents each element (node) in the tree. Each node stores a value and has references to its left and right children.

  • BinarySearchTree Class: Manages the entire tree structure. It includes methods for insertion (insert) and searching (lookUp).

Conclusion

Binary Search Trees are a powerful tool for managing data efficiently. By understanding their structure and implementation, you can leverage BSTs for tasks like database indexing, auto-complete features, and more. Remember, the key to mastering BSTs is practice—try implementing various operations and traversals to solidify your understanding.

Feel free to explore further and experiment with the provided code. Happy coding!

More from this blog

Untitled Publication

30 posts