Kodewick
Start learning →

Binary search tree (BST) in Python, visualized step by step

PythonC

Every node's left subtree holds smaller keys and its right subtree the rest. Insert and search both start at the root: smaller goes left, bigger goes right, one side per level.

binary_search_tree.py
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

def insert(root, key):
    if root is None:
        return Node(key)
    if key < root.key:
        root.left = insert(root.left, key)
    else:
        root.right = insert(root.right, key)
    return root

def search(root, key):
    while root and root.key != key:
        root = root.left if key < root.key else root.right
    return root is not None

root = None
for k in [8, 3, 10, 1, 6, 14]:
    root = insert(root, k)
print(search(root, 6), search(root, 7))
Press ▶ to play, or ‹ › to stepEdit this code in the online compiler ↗

How Binary search tree works

  1. Start at the root and compare the key with the current node.
  2. Smaller: go left; otherwise go right.
  3. Insert: at an empty spot, put the new node there.
  4. Search: an equal key is found; reaching an empty spot means it is not in the tree.

What to watch

The pathOne step left or right per level: count the nodes it passes.
Where a new node hangs6 is smaller than 8 (left) and bigger than 3 (right), so it hangs right of 3.

FAQ

What is the time complexity of searching a BST?

Proportional to the tree's height: O(log n) when it is balanced, O(n) when sorted input turns it into a line.

How do you avoid that?

Use a self-balancing tree such as an AVL or red-black tree; C++'s std::map is a red-black tree.

What does an in-order traversal of a BST give?

The keys in sorted order, smallest first.

More algorithms

All 10 algorithm visualizations →