Mental Model
We want to find how many pieces (nodes) are in a tree by visiting each one exactly once.
Analogy: Imagine counting all the people in a family tree by visiting each person and adding one to your count.
1 / \ 2 3 / 4
1 / \ 2 3 / 4
Count so far: 1 (node 1)
Count so far: 2 (nodes 1, 2)
Count so far: 3 (nodes 1, 2, 4)
Return 1 from node 4
Return 0 from right child of node 2
Return 2 from node 2
Count so far: 1 (node 3)
Return 1 from node 3
Return 4 from root node
1 -> 2 -> 4 -> null and 3 -> null Total nodes counted: 4
package main import "fmt" type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func countNodes(root *TreeNode) int { if root == nil { return 0 } leftCount := countNodes(root.Left) // count nodes in left subtree rightCount := countNodes(root.Right) // count nodes in right subtree return 1 + leftCount + rightCount // add current node } func main() { // Build tree: 1 // / \ // 2 3 // / // 4 root := &TreeNode{Val: 1} root.Left = &TreeNode{Val: 2} root.Right = &TreeNode{Val: 3} root.Left.Left = &TreeNode{Val: 4} total := countNodes(root) fmt.Printf("Total nodes counted: %d\n", total) }
if root == nil {
return 0
}leftCount := countNodes(root.Left)rightCount := countNodes(root.Right)return 1 + leftCount + rightCountif root == nil { return 0 }
return 1 + leftCount + rightCount
leftCount := countNodes(root.Left) rightCount := countNodes(root.Right)