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
- Check the dict before calling: `if not tree: ...` and handle the empty case explicitly
- Fix the upstream builder so an empty tree is not silently produced (log when zero nodes are parsed)
- 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
- Never build an adjacency dict without asserting at least one node was parsed
- Log when a tree builder returns zero entries
- Treat an empty tree as a valid edge case at the caller, not inside the library
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
- Binary search tree is empty
- root {root} is not present in the binary_tree
- Warning: Tree is empty! please use another.
- Value {value} not found
- Node with label {label} already exists
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/cb86a2e4a13d6fb9.
Report an issue: GitHub.