DSA Tracker

Medium

Count Total Nodes in Complete Binary Tree

A medium Binary Trees problem included in Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Binary Trees
Sheets
1
Core for
4 roles
Platform
LeetCode

The problem

Given the root of a complete binary tree, return the number of nodes in the tree. A complete binary tree has all levels fully filled except possibly the last, which is filled from left to right.

Example 1

Input
[1,2,3,4,5,6]
Output
6
Why
The tree has 6 nodes total.

Example 2

Input
[]
Output
0
Why
An empty tree has zero nodes.

Example 3

Input
[1]
Output
1
Why
A single node tree has one node.

Constraints

  • The number of nodes is in the range [0, 5 * 104].
  • -104 <= Node.val <= 104

How to think about it

Updated 2026-09-09

In a complete binary tree, at least one of every node's two subtrees is a perfect binary tree. A perfect tree of height h has exactly 2^h - 1 nodes, computed in O(1) without traversal. Check whether the leftmost and rightmost depths match: if they do, use the formula; if not, recurse on children.

Approaches, worst first

  1. Standard tree traversal

    time O(n) · space O(h)

    Count nodes using simple recursion: `1 + count(left) + count(right)`. Completely ignores the completeness property and visits every single node.

  2. Divide and conquer with height checksWrite this one

    time O(log^2 n) · space O(log n)

    Measure leftmost depth and rightmost depth. If equal, return `(1 << leftDepth) - 1`. If unequal, recursively compute `1 + countNodes(node.left) + countNodes(node.right)`. At each level, one subtree is guaranteed to be perfect, halving the search.

Where people lose marks · 3
  • Bit shifting `1 << 31` causes 32-bit signed integer overflow in some environments; use `Math.pow(2, h) - 1` or proper bitwise limits.
  • Measuring depth by traversing both children rather than strictly following left-only and right-only spines wastes subproblem speedups.
  • Returning 0 when root is null must be the base case before calculating heights.

The theory behind it

Binary Trees — the ground this problem stands on. All Binary Trees problems

What Binary Trees is

A binary tree is a branching data structure that starts at a single top node called the root, like an upside-down family tree. Every node holds a piece of data and can branch out to at most two children below it, known as the left child and the right child. Because there is no ordering rule about which values go left or right, finding a specific item can require checking every single node in the entire tree.

When to reach for it

Reach for binary trees when problems present hierarchical data with left and right child pointers. Questions asking for tree height, maximum depth, path sums from root to leaf, diameter, lowest common ancestor, or checking whether two trees are mirror reflections of each other all signal binary tree traversals. Any problem asking to inspect or reconstruct a tree layer by layer or path by path belongs here.

How the pattern works

Think recursively by focusing on what a single node must do. If the current node is null, return the base answer immediately. Otherwise, ask the left child for its result, ask the right child for its result, and combine both answers with the current node value before returning up to the parent. For horizontal scans, use a queue to read nodes layer by layer, measuring the queue length at the start of each layer to group nodes by depth.

What each operation costs

OperationTime
traverse all nodes using recursion or queueO(n)
search for an arbitrary value in an unordered treeO(n)
call stack memory on balanced treeO(log n)
call stack memory on skewed treeO(n)
What usually goes wrong with Binary Trees
  • Dereferencing left or right child pointers without checking if the current node is null, throwing null pointer errors on empty trees or leaf nodes.
  • Defining a leaf node incorrectly by stopping when either child is null instead of checking that both left and right children are simultaneously null.
  • Computing tree diameter by taking left height plus right height inside a recursive helper without updating a global maximum across every visited node.

Which roles need this problem

Binary Trees is a core topic for these 4 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 5 more roles, including Full-Stack Developer, Android Developer, iOS Developer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Binary Trees problems

Problem set and role mapping as of .