TheAlgorithms/Python · error · ValueError

binary tree cannot be empty

Error message

binary tree cannot be empty

What it means

Raised by binary_tree_mirror(binary_tree, root) when the binary_tree adjacency dict is falsy ({} or None). The function mirrors a dict-of-lists tree representation; an empty dict has no root to start the recursive swap, so it refuses with ValueError before doing work. Note the function also copies the input (dict(binary_tree)) — it never mutates the caller's tree.

Source

Thrown at data_structures/binary_tree/binary_tree_mirror.py:32


def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict:
    """
    >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 7: [8,9]}, 1)
    {1: [3, 2], 2: [5, 4], 3: [7, 6], 7: [9, 8]}
    >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 1)
    {1: [3, 2], 2: [5, 4], 3: [7, 6], 4: [11, 10]}
    >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 5)
    Traceback (most recent call last):
        ...
    ValueError: root 5 is not present in the binary_tree
    >>> binary_tree_mirror({}, 5)
    Traceback (most recent call last):
        ...
    ValueError: binary tree cannot be empty
    """
    if not binary_tree:
        raise ValueError("binary tree cannot be empty")
    if root not in binary_tree:
        msg = f"root {root} is not present in the binary_tree"
        raise ValueError(msg)
    binary_tree_mirror_dictionary = dict(binary_tree)
    binary_tree_mirror_dict(binary_tree_mirror_dictionary, root)
    return binary_tree_mirror_dictionary


if __name__ == "__main__":
    binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]}
    print(f"Binary tree: {binary_tree}")
    binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5)
    print(f"Binary tree mirror: {binary_tree_mirror_dictionary}")

View on GitHub (pinned to f5988cc097)

Solutions

  1. Check the dict before calling: `if not tree: ...` and handle the empty case explicitly
  2. Fix the upstream builder so an empty tree is not silently produced (log when zero nodes are parsed)
  3. Wrap the call in try/except ValueError if the empty case is legitimately possible in your flow

Example fix

# before
mirrored = binary_tree_mirror(adj, root)  # adj == {}

# after
if adj:
    mirrored = binary_tree_mirror(adj, root)
else:
    mirrored = {}
Defensive patterns

Strategy: validation

Validate before calling

def mirror_or_none(tree: dict) -> dict | None:
    if not tree:
        return None
    return binary_tree_mirror(tree, next(iter(tree)))

Type guard

def is_nonempty_tree(tree: object) -> bool:
    return isinstance(tree, dict) and len(tree) > 0 and all(isinstance(v, list) and len(v) == 2 for v in tree.values())

Try / catch

try:
    mirrored = binary_tree_mirror(tree, root)
except ValueError as e:
    if "cannot be empty" not in str(e):
        raise
    mirrored = {}

Prevention

When it happens

Trigger: binary_tree_mirror({}, 1) with an empty dict; passing a tree dict that a previous step built as {} because the parser/source produced no edges.

Common situations: Building the adjacency dict from user input or a file that yielded no nodes; upstream filtering that removed all entries; default-initialized dict never populated.

Related errors


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