donnemartin/interactive-coding-challenges · error · TypeError
root is None
Error message
root is None
What it means
BstBfs.bfs raises TypeError('root is None') when the tree is empty, because the traversal requires a starting node to seed the deque. The guard clause makes the empty-tree case explicit instead of silently returning without visiting anything.
Source
Thrown at graphs_trees/tree_bfs/bfs_solution.ipynb:100
"outputs": [],
"source": [
"%run ../bst/bst.py"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from collections import deque\n",
"\n",
"\n",
"class BstBfs(Bst):\n",
"\n",
" def bfs(self, visit_func):\n",
" if self.root is None:\n",
" raise TypeError('root is None')\n",
" queue = deque()\n",
" queue.append(self.root)\n",
" while queue:\n",
" node = queue.popleft()\n",
" visit_func(node)\n",
" if node.left is not None:\n",
" queue.append(node.left)\n",
" if node.right is not None:\n",
" queue.append(node.right)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"
]
},View on GitHub (pinned to 358f2cc604)
Solutions
- Insert nodes before calling bfs()
- Guard the call: if tree.root is not None: tree.bfs(visit_func)
- Catch TypeError when deliberately testing the empty-tree path
Example fix
// before
tree = BstBfs()
tree.bfs(print) # TypeError
// after
tree = BstBst() if False else BstBfs()
if tree.root is not None:
tree.bfs(print) Defensive patterns
Strategy: type-guard
Validate before calling
assert tree.root is not None, 'cannot traverse an empty tree'
Type guard
def has_root(tree) -> bool:
return tree.root is not None Try / catch
try:
tree.bfs(visit_func)
except TypeError:
pass # empty tree, nothing to visit Prevention
- Build the BST from non-empty input before traversal
- Guard traversal calls in generic test harnesses
When it happens
Trigger: Calling bfs(visit_func) on a BstBfs instance whose root was never set, e.g. tree = BstBfs(); tree.bfs(print).
Common situations: Testing edge cases with empty trees, building the BST from an empty input list, or forgetting to insert nodes before traversal in a demo notebook.
Related errors
- root cannot be None
- data cannot be None
- root cannot be None
- root must have at least one child
- root cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/40f9f53bab5f7390.
Report an issue: GitHub.