PatternsBinary Search Tree (BST) Pattern

Binary Search Tree (BST) Pattern

Master the principles of Binary Search Trees to efficiently insert, delete, search, and traverse hierarchical data structures used in many classic coding problems.

0 Problems
4-5 Hours
Easy to Hard

When to Use Binary Search Tree (BST) Pattern

Efficient Search

When you need faster than linear time search in a sorted data structure

Hierarchical Data

Modeling or parsing data with a parent-child structure

Sorted Insertion

When insertions must maintain sorted order without re-sorting

Inorder Traversal

Extracting sorted data from a tree efficiently

Key Insights & Tips

Inorder = Sorted

Inorder traversal of BST always gives sorted order

Time Complexity

O(log n) on average for insert/search/delete in balanced BST

Common Mistake

Not handling duplicate values correctly or improperly updating node references

Space Usage

O(h) recursive stack space for operations where h = height of BST

Code Examples

Insert into BST

Recursive insertion maintaining BST properties

Time: O(log n) avg, O(n) worstSpace: O(h) recursive stack
class TreeNode {
    val: number;
    left: TreeNode | null;
    right: TreeNode | null;

    constructor(val = 0, left = null, right = null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

function insertIntoBST(root: TreeNode | null, val: number): TreeNode {
    if (!root) return new TreeNode(val);

    if (val < root.val) {
        root.left = insertIntoBST(root.left, val);
    } else {
        root.right = insertIntoBST(root.right, val);
    }

    return root;
}

Search in BST

Simple recursive search for a value in BST

Time: O(log n) avg, O(n) worstSpace: O(h)
function searchBST(root: TreeNode | null, val: number): TreeNode | null {
    if (!root || root.val === val) return root;

    if (val < root.val) {
        return searchBST(root.left, val);
    } else {
        return searchBST(root.right, val);
    }
}

Inorder Traversal

Retrieve sorted values using inorder traversal

Time: O(n)Space: O(h)
function inorderTraversal(root: TreeNode | null): number[] {
    const result: number[] = [];

    function traverse(node: TreeNode | null) {
        if (!node) return;
        traverse(node.left);
        result.push(node.val);
        traverse(node.right);
    }

    traverse(root);
    return result;
}

Your Progress

Problems Solved0/15
0% Complete15 remaining

Practice Problems

View All

Asked by Companies

AmazonGoogleMicrosoftFacebookBloombergAdobe

Next Pattern

Ready for the next challenge?

Tree Traversals