TheAlgorithms/Python · error · TypeError
Value must be an integer.
Error message
Value must be an integer.
What it means
Raised by TreeNode.__post_init__ (dataclasses/serialize_deserialize_binary_tree.py) when the value field is not an int. The dataclass validates its value immediately after construction, so TreeNode('1'), TreeNode(1.0), or TreeNode(None) all fail with TypeError. Note bool is an int subclass and passes; the check is isinstance(self.value, int), so True/False are accepted.
Source
Thrown at data_structures/binary_tree/serialize_deserialize_binary_tree.py:24
@dataclass
class TreeNode:
"""
A binary tree node has a value, left child, and right child.
Props:
value: The value of the node.
left: The left child of the node.
right: The right child of the node.
"""
value: int = 0
left: TreeNode | None = None
right: TreeNode | None = None
def __post_init__(self):
if not isinstance(self.value, int):
raise TypeError("Value must be an integer.")
def __iter__(self) -> Iterator[TreeNode]:
"""
Iterate through the tree in preorder.
Returns:
An iterator of the tree nodes.
>>> list(TreeNode(1))
[1,null,null]
>>> tuple(TreeNode(1, TreeNode(2), TreeNode(3)))
(1,2,null,null,3,null,null, 2,null,null, 3,null,null)
"""
yield self
yield from self.left or ()
yield from self.right or ()
def __len__(self) -> int:View on GitHub (pinned to f5988cc097)
Solutions
- Convert before constructing: TreeNode(int(raw)) for string input
- Sanitize at the parse boundary: `int(value.strip())` right after reading tokens
- If non-int payloads are legitimate, copy the dataclass and widen the field type instead of fighting the guard
Example fix
# before
node = TreeNode('5') # TypeError
# after
node = TreeNode(int('5')) Defensive patterns
Strategy: type-guard
Validate before calling
from data_structures.binary_tree.serialize_deserialize_binary_tree import TreeNode node = TreeNode(value) if isinstance(value, int) and not isinstance(value, bool) else TreeNode(int(value))
Type guard
def is_int_value(v: object) -> bool:
"""True for real ints (excluding bool, which the dataclass accepts)."""
return isinstance(v, int) Try / catch
try:
node = TreeNode(raw)
except TypeError:
node = TreeNode(int(raw)) # coerce string/float payloads Prevention
- Convert to int at the parse boundary (int(x.strip()) for text/CSV tokens)
- Do not feed JSON string numbers straight into TreeNode
- Remember bool passes the check; normalize True/False if they leak in
When it happens
Trigger: TreeNode('5') with a string (typical when building nodes from unparsed text/JSON); TreeNode(1.5) from float math; TreeNode(None) as a 'missing' marker; passing a numpy int64 (isinstance check may pass since it subclasses int in some builds, but plain object dtype values will fail).
Common situations: Deserializing JSON where numbers arrive as strings; reading node values from CSV/text without int() conversion; mixing float coordinates into a tree meant for integer labels.
Related errors
- operation can not be conducted on an object of type {type(nu
- Input value must be an 'int' type
- plaintext must be a string
- key must be a string
- ciphertext must be a string
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/c3c8d1e8a18768b2.
Report an issue: GitHub.