All algorithms
Trees

Binary Search Tree

An ordered tree where left < node < right — insert, search and traverse.

TimeO(h)SpaceO(n)CategoryTrees

A Binary Search Tree keeps its keys ordered: everything in a node's left subtree is smaller, everything in the right subtree is larger. That invariant makes search, insert, and delete run in O(h) time, where h is the height of the tree.

BSTs are the foundation for balanced trees (AVL, red-black) and for understanding `std::set` / `std::map`. The classic pitfall is that an unbalanced BST degrades to a linked list — seeing the tree shape is the best way to build that intuition.

AlgoLens renders the tree from the real pointers in memory, so you watch each insertion walk down the correct path and attach a new node.

The code

binary_search_tree.cpp
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int val;
    Node* left;
    Node* right;
};

Node* insert(Node* root, int x) {
    if (root == nullptr) return new Node{x, nullptr, nullptr};
    if (x < root->val) root->left = insert(root->left, x);
    else root->right = insert(root->right, x);
    return root;
}

int main() {
    Node* root = nullptr;
    for (int x : {5, 3, 8, 1, 4, 7, 9}) {
        root = insert(root, x);
    }
    cout << root->val << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Binary Search Tree

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going