TheAlgorithms/Python · error · ValueError

Node with label {label} does not exist

Error message

Node with label {label} does not exist

What it means

Raised by BinarySearchTree.search() (via _search) when the recursion walks off the tree without finding the label. _search descends left/right by comparison; reaching a None node means the key is absent, so a ValueError (not KeyError) signals a missing node. Also fires on an empty tree, since self.root is None immediately.

Source

Thrown at data_structures/binary_tree/binary_search_tree_recursive.py:107

        Searches a node in the tree

        >>> t = BinarySearchTree()
        >>> t.put(8)
        >>> t.put(10)
        >>> node = t.search(8)
        >>> assert node.label == 8

        >>> node = t.search(3)
        Traceback (most recent call last):
            ...
        ValueError: Node with label 3 does not exist
        """
        return self._search(self.root, label)

    def _search(self, node: Node | None, label: int) -> Node:
        if node is None:
            msg = f"Node with label {label} does not exist"
            raise ValueError(msg)
        elif label < node.label:
            node = self._search(node.left, label)
        elif label > node.label:
            node = self._search(node.right, label)

        return node

    def remove(self, label: int) -> None:
        """
        Removes a node in the tree

        >>> t = BinarySearchTree()
        >>> t.put(8)
        >>> t.put(10)
        >>> t.remove(8)
        >>> assert t.root.label == 10

        >>> t.remove(3)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Wrap search in try/except ValueError and treat it as a miss (this is the intended API contract, per the doctest)
  2. Validate the key exists first by scanning `label in (n.label for n in t.inorder_traversal())` when performance is not critical
  3. Ensure insertion completed before the lookup phase (check for failed earlier put calls that raised error 160)

Example fix

# before
node = t.search(maybe_missing)  # ValueError

# after
try:
    node = t.search(maybe_missing)
except ValueError:
    node = None
Defensive patterns

Strategy: try-catch

Validate before calling

def contains(t, label: int) -> bool:
    try:
        t.search(label)
        return True
    except ValueError:
        return False

Try / catch

try:
    node = t.search(label)
except ValueError:
    node = None  # documented miss path, per the module's doctest

Prevention

When it happens

Trigger: t.search(label) where label was never inserted; searching an empty tree (`BinarySearchTree().search(5)`); searching for a value removed earlier via t.remove().

Common situations: Looking up user-supplied IDs that may not exist; searching after deletions; forgetting to populate the tree before a lookup phase.

Related errors


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