Mental Model
We want to find how many boxes (nodes) are in a tree by visiting each one exactly once.
Analogy: Imagine counting all the rooms in a house by walking through every hallway and door until you have seen every room.
1 / \ 2 3 / \ 4 5
1 / \ 2 3 / \ 4 5
Count so far: 1 (node 1)
Count so far: 2 (nodes 1, 2)
Count so far: 3 (nodes 1, 2, 4)
Count so far: 3 (nodes 1, 2, 4)
Count so far: 4 (nodes 1, 2, 4, 5)
Count so far: 4 (nodes 1, 2, 4, 5)
Count so far: 5 (nodes 1, 2, 4, 5, 3)
Count so far: 5 (all nodes counted)
Final count: 5 nodes
class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } } function countNodes(root) { if (root === null) return 0; // base case: no node here // count current node plus left subtree plus right subtree return 1 + countNodes(root.left) + countNodes(root.right); } // Build the tree from dry run example const root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); const totalNodes = countNodes(root); console.log(totalNodes);
if (root === null) return 0; // base case: no node herereturn 1 + countNodes(root.left) + countNodes(root.right);if (root === null) return 0; // base case: no node here
return 1 + countNodes(root.left) + countNodes(root.right);