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 TreeCounting 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
- If the current node is null, return 0 (base case, nothing to count).
- Recursively count the nodes in the left subtree.
- Recursively count the nodes in the right subtree.
- 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)
- count(4) = 1 + count(null) + count(null) = 1
- count(2) = 1 + count(4) + count(null) = 1 + 1 + 0 = 2
- count(3) = 1
- count(root) = 1 + count(2) + count(3) = 1 + 2 + 1 = 4
Output: 4
Press ▶ Run to watch it step by step.
def count_nodes(root):
if not root:
return 0
return 1 + count_nodes(root.left) + count_nodes(root.right)
# example: count nodesBehind 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
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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.