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?"
Practice
Solution
Step 1: Understand node counting in binary tree
Counting total nodes means including every node: root, left child, and right child recursively.Step 2: Compare options with definition
Only the option that says 'It counts all nodes including root, left, and right children.' includes all nodes, others limit to parts of the tree.Final Answer:
It counts all nodes including root, left, and right children. -> Option BQuick Check:
Total nodes = all nodes in tree [OK]
- Counting only leaf nodes
- Ignoring root node
- Counting only one subtree
Solution
Step 1: Identify correct parameter type
Binary tree root is usually a pointer to Node, so *Node is correct.Step 2: Identify correct return type
Counting nodes returns an integer, so return type int is correct.Final Answer:
func countNodes(root *Node) int -> Option CQuick Check:
Pointer parameter and int return type [OK]
- Passing Node by value instead of pointer
- Returning wrong type like string or bool
- Missing pointer in parameter
package main
import "fmt"
type Node struct {
Val int
Left *Node
Right *Node
}
func countNodes(root *Node) int {
if root == nil {
return 0
}
return 1 + countNodes(root.Left) + countNodes(root.Right)
}
func main() {
root := &Node{Val: 1}
root.Left = &Node{Val: 2}
root.Right = &Node{Val: 3}
root.Left.Left = &Node{Val: 4}
fmt.Println(countNodes(root))
}Solution
Step 1: Count nodes in the tree structure
Nodes are: 1 (root), 2 (left), 3 (right), 4 (left-left). Total = 4 nodes.Step 2: Verify counting logic in code
Code counts root + left subtree + right subtree recursively, so total nodes = 4.Final Answer:
4 -> Option DQuick Check:
Count nodes recursively = 4 [OK]
- Counting only root and immediate children
- Forgetting to count left-left node
- Misreading tree structure
func countNodes(root *Node) int {
if root == nil {
return 1
}
return 1 + countNodes(root.Left) + countNodes(root.Right)
}Solution
Step 1: Check base case for nil node
When root is nil, it means no node, so should return 0, not 1.Step 2: Verify the counting logic
The return statement correctly adds 1 for the current node plus recurses on left and right subtrees.Final Answer:
Returns 1 when root is nil, should return 0. -> Option AQuick Check:
Nil node count = 0, not 1 [OK]
- Returning 1 for nil node
- Not adding 1 for current node
- Incorrect base case logic
Solution
Step 1: Add condition to count only even nodes
Check if current node's value is even; if yes, count 1, else 0.Step 2: Recursively count even nodes in left and right subtrees
Sum counts from left and right subtrees with current node's count.Final Answer:
Add a check: if node value is even, add 1; else add 0, then recurse. -> Option AQuick Check:
Count only even nodes by conditional addition [OK]
- Counting all nodes then subtracting odd nodes
- Skipping subtrees based on node value
- Ignoring node values in count
Ready to prove it?
Pass the test and this pattern moves unknown
