TheAlgorithms/Python · error · ValueError

The nodes number should be same as the number of coins

Error message

The nodes number should be same as the number of coins

What it means

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.

Source

Thrown at data_structures/binary_tree/distribute_coins.py:103

        0
        """
        if node is None:
            return 0

        return count_nodes(node.left) + count_nodes(node.right) + 1

    def count_coins(node: TreeNode | None) -> int:
        """
        >>> count_coins(None)
        0
        """
        if node is None:
            return 0

        return count_coins(node.left) + count_coins(node.right) + node.data

    if count_nodes(root) != count_coins(root):
        raise ValueError("The nodes number should be same as the number of coins")

    # Main calculation
    def get_distrib(node: TreeNode | None) -> CoinsDistribResult:
        """
        >>> get_distrib(None)
        namedtuple("CoinsDistribResult", "0 2")
        """

        if node is None:
            return CoinsDistribResult(0, 1)

        left_distrib_moves, left_distrib_excess = get_distrib(node.left)
        right_distrib_moves, right_distrib_excess = get_distrib(node.right)

        coins_to_left = 1 - left_distrib_excess
        coins_to_right = 1 - right_distrib_excess

        result_moves = (

View on GitHub (pinned to f5988cc097)

Solutions

  1. Recount and rebalance: adjust node.data values so sum(data) == number of nodes (e.g. set all to 1 as the canonical case)
  2. Validate the precondition in your builder: `assert sum_of_data(root) == count_nodes(root)` with a clear failure message
  3. If you actually need arbitrary coin totals, this function is the wrong tool — use a general excess/flow calculation without the precondition

Example fix

# before
# root has 3 nodes but data values sum to 5 -> ValueError
root = TreeNode(2, TreeNode(1), TreeNode(2))

# after
root = TreeNode(1, TreeNode(1), TreeNode(1))
print(distribute_coins(root))  # 0
Defensive patterns

Strategy: validation

Validate before calling

def _count(n):
    return 0 if n is None else 1 + _count(n.left) + _count(n.right)

def _coins(n):
    return 0 if n is None else _coins(n.left) + _coins(n.right) + n.data

assert _count(root) == _coins(root), 'precondition: coins must equal node count'

Try / catch

try:
    moves = distribute_coins(root)
except ValueError:
    raise ValueError('tree violates 1-coin-per-node average; check node.data values') from None

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


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