donnemartin/interactive-coding-challenges · error · TypeError
root cannot be None
Error message
root cannot be None
What it means
InverseBst.invert_tree raises TypeError('root cannot be None') when called on an empty BST. The class delegates to _invert_tree starting from self.root, and the guard clause treats an empty tree as an invalid argument rather than a no-op, so callers must ensure the tree has at least one node before inverting.
Source
Thrown at graphs_trees/invert_tree/invert_tree_solution.ipynb:114
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"%run ../bst/bst.py"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"class InverseBst(Bst):\n",
"\n",
" def invert_tree(self):\n",
" if self.root is None:\n",
" raise TypeError('root cannot be None')\n",
" return self._invert_tree(self.root)\n",
"\n",
" def _invert_tree(self, root):\n",
" if root is None:\n",
" return\n",
" self._invert_tree(root.left)\n",
" self._invert_tree(root.right)\n",
" root.left, root.right = root.right, root.left\n",
" return root"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"
]
},View on GitHub (pinned to 358f2cc604)
Solutions
- Insert at least one node (e.g. tree.insert(5)) before calling invert_tree()
- Guard the call: if tree.root is not None: tree.invert_tree()
- Catch TypeError in test code when intentionally exercising the empty-tree case
Example fix
// before
tree = InverseBst()
tree.invert_tree() # TypeError
// after
tree = InverseBst()
if tree.root is not None:
tree.invert_tree() Defensive patterns
Strategy: type-guard
Validate before calling
assert tree.root is not None, 'cannot invert an empty tree'
Type guard
def can_invert(tree) -> bool:
return tree.root is not None Try / catch
try:
tree.invert_tree()
except TypeError:
pass # empty tree, nothing to invert Prevention
- Always insert at least one node before calling tree operations
- Wrap notebook demos with a root check to handle empty-tree edge cases
When it happens
Trigger: Calling invert_tree() on a freshly constructed InverseBst (or any Bst subclass) without inserting any nodes first, e.g. tree = InverseBst(); tree.invert_tree().
Common situations: Running the solution on an empty test case, initializing a BST from an empty array/list, or a test harness that iterates over edge cases including [] before populated trees.
Related errors
- data cannot be None
- root cannot be None
- root must have at least one child
- node cannot be None
- root cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/70c62d4cd9435677.
Report an issue: GitHub.