{"record":{"id":"b1679a89f579b4fd","repo":"TheAlgorithms/Python","slug":"the-nodes-number-should-be-same-as-the-number-of-c","errorCode":null,"errorMessage":"The nodes number should be same as the number of coins","messagePattern":"The nodes number should be same as the number of coins","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"data_structures/binary_tree/distribute_coins.py","lineNumber":103,"sourceCode":"        0\n        \"\"\"\n        if node is None:\n            return 0\n\n        return count_nodes(node.left) + count_nodes(node.right) + 1\n\n    def count_coins(node: TreeNode | None) -> int:\n        \"\"\"\n        >>> count_coins(None)\n        0\n        \"\"\"\n        if node is None:\n            return 0\n\n        return count_coins(node.left) + count_coins(node.right) + node.data\n\n    if count_nodes(root) != count_coins(root):\n        raise ValueError(\"The nodes number should be same as the number of coins\")\n\n    # Main calculation\n    def get_distrib(node: TreeNode | None) -> CoinsDistribResult:\n        \"\"\"\n        >>> get_distrib(None)\n        namedtuple(\"CoinsDistribResult\", \"0 2\")\n        \"\"\"\n\n        if node is None:\n            return CoinsDistribResult(0, 1)\n\n        left_distrib_moves, left_distrib_excess = get_distrib(node.left)\n        right_distrib_moves, right_distrib_excess = get_distrib(node.right)\n\n        coins_to_left = 1 - left_distrib_excess\n        coins_to_right = 1 - right_distrib_excess\n\n        result_moves = (","sourceCodeStart":85,"sourceCodeEnd":121,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/binary_tree/distribute_coins.py#L85-L121","documentation":"Raised by distribute_coins() when count_nodes(root) != count_coins(root): the puzzle this solves (LeetCode 933-style coin distribution) is only well-defined when the tree holds exactly one coin per node on average, i.e. total coins equal total nodes. The function enforces that precondition with ValueError before running the moves calculation, so an arbitrary tree with arbitrary coin counts is rejected.","triggerScenarios":"Building a TreeNode tree where node.data values (coin counts) sum to something other than the node count, e.g. some nodes hold 0 coins and others hold 2+, but totals mismatch; test fixtures with hand-set data fields that violate the invariant.","commonSituations":"Porting test data from a different problem; mutating a valid tree by changing data on one node without compensating elsewhere; off-by-one in fixture construction.","solutions":["Recount and rebalance: adjust node.data values so sum(data) == number of nodes (e.g. set all to 1 as the canonical case)","Validate the precondition in your builder: `assert sum_of_data(root) == count_nodes(root)` with a clear failure message","If you actually need arbitrary coin totals, this function is the wrong tool — use a general excess/flow calculation without the precondition"],"exampleFix":"# before\n# root has 3 nodes but data values sum to 5 -> ValueError\nroot = TreeNode(2, TreeNode(1), TreeNode(2))\n\n# after\nroot = TreeNode(1, TreeNode(1), TreeNode(1))\nprint(distribute_coins(root))  # 0","handlingStrategy":"validation","validationCode":"def _count(n):\n    return 0 if n is None else 1 + _count(n.left) + _count(n.right)\n\ndef _coins(n):\n    return 0 if n is None else _coins(n.left) + _coins(n.right) + n.data\n\nassert _count(root) == _coins(root), 'precondition: coins must equal node count'","typeGuard":null,"tryCatchPattern":"try:\n    moves = distribute_coins(root)\nexcept ValueError:\n    raise ValueError('tree violates 1-coin-per-node average; check node.data values') from None","preventionTips":["Default all node.data to 1 unless you deliberately rebalance totals","Validate sum(data) == node count in tree-building tests","Keep fixtures for this problem exactly as given by the original problem statement"],"tags":["binary-tree","precondition","coins","invariant"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}