Ready — insert values to build the tree
Speed
🎨 Customize Colors
Scene Background
Node Color
Text Color
Connection Color

🌳 Binary Search Tree

A Binary Search Tree (BST) is a hierarchical data structure where each node has at most two children. For any node, all elements in the left subtree are smaller, and all elements in the right subtree are larger.

⏱ Average Access: O(log n) ⏱ Average Search: O(log n) ⏱ Average Insert: O(log n) ⏱ Worst Case: O(n)
Python
class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key

def insert(node, key):
    if node is None:
        return Node(key)
    if key < node.val:
        node.left = insert(node.left, key)
    else:
        node.right = insert(node.right, key)
    return node
JavaScript
class Node {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

function insert(root, val) {
    if (!root) return new Node(val);
    if (val < root.val) {
        root.left = insert(root.left, val);
    } else {
        root.right = insert(root.right, val);
    }
    return root;
}