Binary search trees

Left children are smaller, right children are larger. Search, insert, and delete all follow that rule — then traverse the tree three different ways.

Data structures Intermediate BST · Traversals ~12 min
The idea

Ordered by left and right

In a binary search tree (BST), every node’s left subtree holds smaller values and its right subtree holds larger ones. Searching, inserting, and deleting all walk down one path — left or right — by comparing against the current node.

Deletion has three cases: a leaf, a node with one child, or a node with two children (replace it with its inorder successor). Traversals visit every node: inorder (left → root → right) yields sorted order; preorder and postorder change when the root is visited.

TipInorder on a BST prints values in ascending order — that’s the payoff of the left/right rule.
IdeaCore rule
bst_rule.pyPython
# For every node:
#   left  < node.value
#   right > node.value

def search(node, x):
    if node is None:
        return False
    if x == node.value: return True
    if x < node.value:
        return search(node.left, x)
    return search(node.right, x)

Each comparison discards one whole side of the tree.

Interactive

Run the simulation

Switch tabs for insert, delete, and the three classic traversals.

Step 0 / 0
demo.pyPython
Tree + variablesdemo
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Try it yourself

Build and walk your own tree

Insert, search, and delete values, then run a traversal to see the visit order.

Ready
Tree is empty. Enter a value and press Insert.
Remember

BST mental model

One comparison rule powers search, insert, delete, and sorted walks.

Search

One path, left or right

Compare with the current node; go left if smaller, right if larger, until you match or hit None.

Delete

Three cases

Leaf, one child, or two children (swap with the inorder successor, then remove that leaf).

Walks

Three traversals

Inorder → sorted; preorder → root first; postorder → root last (children first).