Mental Model
We want to find how many pieces (nodes) are in a tree by visiting each piece once.
Analogy: Imagine counting all the apples on a tree by checking every branch and every apple one by one.
1 / \ 2 3 / 4
1 / \ 2 3 / 4
Counting node 1
Counting node 2
Counting node 4
Return from node 4 with count 1
Return from node 2 with count 2
Counting node 3
Return from node 3 with count 1
Total nodes counted: 4
1 -> 2 -> 4 -> null (left subtree), 3 -> null (right subtree), total nodes = 4
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def count_nodes(root): if root is None: return 0 left_count = count_nodes(root.left) # count nodes in left subtree right_count = count_nodes(root.right) # count nodes in right subtree return 1 + left_count + right_count # current node + left + right # Driver code root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) print(count_nodes(root))
if root is None:
return 0left_count = count_nodes(root.left)right_count = count_nodes(root.right)return 1 + left_count + right_countif root is None: return 0
return 1 + left_count + right_count
left_count = count_nodes(root.left)
count_nodes that takes a parameter root?def keyword followed by the function name and parameters in parentheses.def count_nodes(root): which is valid Python syntax.class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def count_nodes(root):
if root is None:
return 0
return 1 + count_nodes(root.left) + count_nodes(root.right)
root = Node(10)
root.left = Node(5)
root.right = Node(15)
root.left.left = Node(3)
print(count_nodes(root))def count_nodes(root):
if root == None:
return 1
return 1 + count_nodes(root.left) + count_nodes(root.right)Pass the test and this pattern moves unknown