Count Complete Tree Nodes

Easy

Topics
TreeDFSBinary Search

Given the root of a binary tree, return the total number of nodes.

Example 1

425163
left spine — gives the height
The answer counts every node, 6 here. The tree is complete: every level is full except possibly the last, and that last one is filled strictly left to right with no gaps — a guarantee the question expects to be used rather than ignored.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [1,2,3,4,5,6]
Output: 6

Example 2

empty tree
Input:  root = []
Output: 0

Constraints

  • 0 <= number of nodes <= 5*10^4
  • -10^4 <= Node.val <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

Count every node with a simple traversal: total = 1 + nodes in the left subtree + nodes in the right subtree. (For a guaranteed complete tree there is an O(log² n) left/right-spine trick, but the straightforward O(n) count is clear and always correct.)

Approach

  1. Null → 0.
  2. Otherwise 1 + countNodes(left) + countNodes(right).

Dry Run

level order 1 2 3 4 5 6, so the tree is
        1
      /   \
     2     3
    / \   /
   4   5 6
countNodes is the plain recursion, 1 + left + right:
  enter 1
    enter 2
      enter 4    both children null      1 + 0 + 0 = 1
      enter 5    both children null      1 + 0 + 0 = 1
    exit  2                              1 + 1 + 1 = 3
    enter 3
      enter 6    both children null      1 + 0 + 0 = 1
      right is null                              -> 0
    exit  3                              1 + 1 + 0 = 2
  exit  1                                1 + 3 + 2 = 6
answer 6, reached by visiting all 6 nodes and 7 null children.
Here is the same tree under the O(log^2 n) method, which is what being told
"complete" actually buys you:
  node 1   left spine 3, right spine 2   not perfect, recurse
  node 2   left spine 2, right spine 2   perfect -> 2^2 - 1 = 3, never walked
  node 3   left spine 2, right spine 1   not perfect, recurse
  node 6   left spine 1, right spine 1   perfect -> 2^1 - 1 = 1
  total    1 + 3 + 2 = 6
Both give 6, and at this size the difference is invisible. It shows at scale:
measuring the two spines is O(log n), at most one child per level can be
imperfect, so the recursion is O(log n) deep and the total is O(log^2 n) instead
of O(n). Either version needs the null base case -- without it node 4's missing
left child is dereferenced.

Complexity

  • Time — O(n): visits every node once.
  • Space — O(h): recursion stack, height h.

Common Pitfalls

  • The null base case is what terminates the recursion. Without it the first leaf's missing child raises AttributeError: 'NoneType' object has no attribute 'left'.
  • This counts every node in O(n) and ignores that the tree is complete. The O(log^2 n) answer compares left and right heights to recognise a perfect subtree and takes 2^h - 1 for it instead of walking it -- worth raising, because being handed "complete" and not using it is the thing an interviewer is testing.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def countNodes(self, root):
        if not root:
            return 0
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)
SensAI
Beta
Tap the mic to stop voice mode