{"record":{"id":"cb86a2e4a13d6fb9","repo":"TheAlgorithms/Python","slug":"binary-tree-cannot-be-empty","errorCode":null,"errorMessage":"binary tree cannot be empty","messagePattern":"binary tree cannot be empty","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"data_structures/binary_tree/binary_tree_mirror.py","lineNumber":32,"sourceCode":"\n\ndef binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict:\n    \"\"\"\n    >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 7: [8,9]}, 1)\n    {1: [3, 2], 2: [5, 4], 3: [7, 6], 7: [9, 8]}\n    >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 1)\n    {1: [3, 2], 2: [5, 4], 3: [7, 6], 4: [11, 10]}\n    >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 5)\n    Traceback (most recent call last):\n        ...\n    ValueError: root 5 is not present in the binary_tree\n    >>> binary_tree_mirror({}, 5)\n    Traceback (most recent call last):\n        ...\n    ValueError: binary tree cannot be empty\n    \"\"\"\n    if not binary_tree:\n        raise ValueError(\"binary tree cannot be empty\")\n    if root not in binary_tree:\n        msg = f\"root {root} is not present in the binary_tree\"\n        raise ValueError(msg)\n    binary_tree_mirror_dictionary = dict(binary_tree)\n    binary_tree_mirror_dict(binary_tree_mirror_dictionary, root)\n    return binary_tree_mirror_dictionary\n\n\nif __name__ == \"__main__\":\n    binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]}\n    print(f\"Binary tree: {binary_tree}\")\n    binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5)\n    print(f\"Binary tree mirror: {binary_tree_mirror_dictionary}\")\n","sourceCodeStart":14,"sourceCodeEnd":46,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/binary_tree/binary_tree_mirror.py#L14-L46","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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"],"exampleFix":"# before\nmirrored = binary_tree_mirror(adj, root)  # adj == {}\n\n# after\nif adj:\n    mirrored = binary_tree_mirror(adj, root)\nelse:\n    mirrored = {}","handlingStrategy":"validation","validationCode":"def mirror_or_none(tree: dict) -> dict | None:\n    if not tree:\n        return None\n    return binary_tree_mirror(tree, next(iter(tree)))","typeGuard":"def is_nonempty_tree(tree: object) -> bool:\n    return isinstance(tree, dict) and len(tree) > 0 and all(isinstance(v, list) and len(v) == 2 for v in tree.values())","tryCatchPattern":"try:\n    mirrored = binary_tree_mirror(tree, root)\nexcept ValueError as e:\n    if \"cannot be empty\" not in str(e):\n        raise\n    mirrored = {}","preventionTips":["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"],"tags":["binary-tree","empty-state","adjacency-list","mirror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}