Data Structures · Visualization

Binary Tree: Count Nodes

Binary Tree

Counting nodes means finding the total number of nodes in the tree. Time: O(n). Space: O(h) for the recursion stack.

Big-O: Traversals visit every node exactly once: O(n).

Binary Tree: Count Nodes

Binary Tree

Counting nodes means finding the total number of nodes in the tree. Recursively, the count of a tree is 1 (for the current node) plus the count of its left subtree plus the count of its right subtree.

How Count Nodes Works

  1. If the current node is null, return 0 (base case, nothing to count).
  2. Recursively count the nodes in the left subtree.
  3. Recursively count the nodes in the right subtree.
  4. Return 1 (for the current node) plus both subtree counts.

Count Nodes Worked Example

Input: Tree: root(1) -> left(2), right(3); node(2) -> left(4)

  1. count(4) = 1 + count(null) + count(null) = 1
  2. count(2) = 1 + count(4) + count(null) = 1 + 1 + 0 = 2
  3. count(3) = 1
  4. count(root) = 1 + count(2) + count(3) = 1 + 2 + 1 = 4

Output: 4

Binary Tree: Introduction
A hierarchy of nodes where each node has at most two children — usually called "left" and "right".
45
20
10
30
40
65
50
60
70
80
Active Result
Binary Tree: Introduction
Press ▶ Run to watch it step by step.
Python · Binary Trees in Code
def count_nodes(root):
    if not root:
        return 0
    return 1 + count_nodes(root.left) + count_nodes(root.right)
# example: count nodes
Input: Tree: root(1) -> left(2), right(3); node(2) -> left(4)

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Count Nodes Time & Space Complexity

TimeO(n)
SpaceO(h) for the recursion stack

When to Use Count Nodes

  • Reporting how many items exist in a hierarchical structure
  • Validating tree structure size after insertions/deletions
  • Estimating memory usage for tree-based data

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.