TheAlgorithms/Python · error · ValueError

Binary search tree is empty

Error message

Binary search tree is empty

What it means

Raised by BinarySearchTree.get_max_label() when self.root is None. The max label lives at the rightmost node; an empty tree has no such node, so the method raises ValueError('Binary search tree is empty') before starting the while-walk. It is a straightforward empty-state guard.

Source

Thrown at data_structures/binary_tree/binary_search_tree_recursive.py:202

            return False

    def get_max_label(self) -> int:
        """
        Gets the max label inserted in the tree

        >>> t = BinarySearchTree()
        >>> t.get_max_label()
        Traceback (most recent call last):
            ...
        ValueError: Binary search tree is empty

        >>> t.put(8)
        >>> t.put(10)
        >>> t.get_max_label()
        10
        """
        if self.root is None:
            raise ValueError("Binary search tree is empty")

        node = self.root
        while node.right is not None:
            node = node.right

        return node.label

    def get_min_label(self) -> int:
        """
        Gets the min label inserted in the tree

        >>> t = BinarySearchTree()
        >>> t.get_min_label()
        Traceback (most recent call last):
            ...
        ValueError: Binary search tree is empty

        >>> t.put(8)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Guard the call: `if t.root is not None: max_label = t.get_max_label()`
  2. Use len(t) or the size accessor to check emptiness before querying
  3. Ensure put() calls succeeded earlier — a put that raised error 160 can leave you thinking the tree is populated when it is not

Example fix

# before
m = t.get_max_label()  # ValueError if empty

# after
m = t.get_max_label() if t.root is not None else None
Defensive patterns

Strategy: validation

Validate before calling

max_label = t.get_max_label() if t.root is not None else None

Try / catch

try:
    m = t.get_max_label()
except ValueError:
    m = None  # empty tree

Prevention

When it happens

Trigger: Calling t.get_max_label() on a freshly constructed tree, or after removing all nodes; calling it before any put() in a script.

Common situations: Querying max of a tree populated from an empty/filtered dataset; calling statistics helpers before the data-loading step; reusing a tree object after clearing it.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/c0dee5d4443f16a4. Report an issue: GitHub.