0
0
DSA Goprogramming~5 mins

Count Total Nodes in Binary Tree in DSA Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Count Total Nodes in Binary Tree
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each node is visited exactly once, so the total work grows directly with the number of nodes.

Input Size (n)Approx. Operations
10About 10 visits
100About 100 visits
1000About 1000 visits

Pattern observation: The work grows linearly as the tree size increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to count nodes grows directly in proportion to the number of nodes in the tree.

Common Mistake

[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.

Interview Connect

Understanding this helps you explain how recursive tree algorithms work and how their time depends on tree size, a common interview topic.

Self-Check

"What if we changed the tree to a linked list (all nodes only have one child)? How would the time complexity change?"