Count Total Nodes in Binary Tree in DSA Go - Time & Space Complexity
We want to understand how the time needed to count all nodes in a binary tree changes as the tree grows.
How does the work increase when the tree has more nodes?
Analyze the time complexity of the following code snippet.
func countNodes(root *TreeNode) int {
if root == nil {
return 0
}
leftCount := countNodes(root.Left)
rightCount := countNodes(root.Right)
return 1 + leftCount + rightCount
}
This code counts all nodes by visiting each node once and adding up counts from left and right subtrees.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Once per node in the tree.
Each node is visited exactly once, so the total work grows directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows linearly as the tree size increases.
Time Complexity: O(n)
This means the time to count nodes grows directly in proportion to the number of nodes in the tree.
[X] Wrong: "Counting nodes is faster because we only check the root and skip subtrees sometimes."
[OK] Correct: Every node must be visited to be counted, so skipping any part misses nodes and gives wrong results.
Understanding this helps you explain how recursive tree algorithms work and how their time depends on tree size, a common interview topic.
"What if we changed the tree to a linked list (all nodes only have one child)? How would the time complexity change?"