Problem 222

Abstract / Summary

Count the number of nodes in a complete binary tree by using its structure efficiently.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0222.py

class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        # basic O(n) algorithm
        # solving in better than O(n) requires far mor code and is less versatile
        if not root:
            return 0
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)
7 lines | 313 bytes | submitted September 1, 2023 | GitHub   40% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (1+ million submissions).

Typical patterns to solve this problem:
  • Binary Search
  • Binary Tree
  • Bit Manipulation
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method countNodes. The method receives the root of a binary tree and returns the total number of nodes contained in that tree. The algorithm follows a classic depth-first traversal pattern, visiting each node exactly once and aggregating the counts from the left and right sub-trees.

Key Steps

Handling an Empty Tree

The first logical branch checks whether the supplied root reference is falsy. In Python, a None value indicates that the tree (or a sub-tree) is empty. When this condition is true, the method returns 0, representing the absence of any nodes.

if not root:
    return 0

Recursively Counting Sub-trees

If the tree is not empty, the method proceeds to count the current node and then recursively invokes itself for the left and right children. The recursive calls explore the entire structure, accumulating the node count from each branch.

return 1 + self.countNodes(root.left) + self.countNodes(root.right)

Combining Results

The expression 1 + left_count + right_count combines the contribution of the current node (1) with the totals obtained from the left and right sub-trees. This single return statement encapsulates the entire counting logic.

Edge Cases Addressed

The algorithm gracefully handles several edge conditions without additional code:

  • Empty Tree - The initial if not root guard returns 0, covering the scenario where the input tree has no nodes.
  • Single-Node Tree - When the root exists but both children are None, the recursive calls each hit the empty-tree guard, yielding 0 + 0. The final result is 1, correctly reflecting a solitary node.
  • Highly Unbalanced Trees - The recursion proceeds down whichever side contains nodes, terminating when a leaf’s child reference is None. This ensures that even degenerate structures (e.g., a linked-list-like chain) are counted accurately.

Performance Optimizations Present

Although the algorithm operates in linear time relative to the number of nodes, it incorporates a few implicit efficiencies:

  • Early Termination for Null Sub-trees - By checking if not root at the start of each call, the function avoids unnecessary processing of absent children, reducing the number of recursive invocations.
  • Minimal Overhead in the Return Path - The single return statement eliminates intermediate variables, allowing Python’s interpreter to compute the result with a compact call stack frame.
  • Depth-First Traversal Aligned with Call Stack - The recursion naturally follows the tree’s depth, which means that for balanced trees the maximum call-stack depth is proportional to the tree height (logarithmic in the number of nodes). This keeps memory usage modest compared to a breadth-first approach that would require an explicit queue.

The comment in the source hints at more sophisticated techniques (such as leveraging the properties of a complete binary tree to achieve sub-linear performance), but the current implementation prioritizes clarity and broad applicability.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a giant tree with many branching paths, and at the end of every path there is a little house. This puzzle is like playing a game of hide and seek where the goal is to count how many houses are hidden in the tree.

The computer starts at the very top of the tree. First, it peeks at the spot where it is standing to see if a house is there. If the spot is empty, the computer just stops and says there are zero houses. If there is a house, the computer keeps one in its mind and then sends out two helpers to look further down the branches. One helper goes down the left side and the other helper goes down the right side.

Every time a helper finds a house, that helper adds it to the total count. They keep doing this over and over again on every single branch until every part of the tree has been checked. Once all the little helpers have finished looking everywhere, the computer adds up all the numbers they gathered to know exactly how many houses are in the whole tree.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.70 | σ = 1.58

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# JS Rust Go
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fpdjsns C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
MacJim C++
martianoff Scala
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fpdjsns C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
MacJim C++
martianoff Scala
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
50 links | 34 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Count Complete Tree Nodes -(Amazon, Microsoft, Salesforce, Meta) : Explanation ➕ Live Coding'
codestorywithMIK 22 mins
Count Complete Tree Nodes -(Amazon, Microsoft, Salesforce, Meta) : Explanation ➕ Live Coding
YouTube video 'Count Complete Tree Nodes | LeetCode 222 | C++, Java, Python'
Knowledge Center 14 mins
Count Complete Tree Nodes | LeetCode 222 | C++, Java, Python
YouTube video 'Count Complete Tree Nodes (LeetCode 222) | Complete tree examples | Recursive & Iterative'
Nikhil Lohia 15 mins
Count Complete Tree Nodes (LeetCode 222) | Complete tree examples | Recursive & Iterative
YouTube video 'COUNT COMPLETE TREE NODES (Leetcode) - Code & Whiteboard'
babybear4812 28 mins
COUNT COMPLETE TREE NODES (Leetcode) - Code & Whiteboard
YouTube video 'Daily Leetcode #959: Nov 15, 2022 - 222. Count Complete Tree Nodes'
Programming Live with Larry 20 mins
Daily Leetcode #959: Nov 15, 2022 - 222. Count Complete Tree Nodes
YouTube video '222. Count Complete Tree Nodes | JavaScript | LeetCode Daily Challenge | Detailed Explanation'
LeetCodeWithMonu 16 mins
222. Count Complete Tree Nodes | JavaScript | LeetCode Daily Challenge | Detailed Explanation
YouTube video 'Count Complete Tree Nodes | Day 23 | Binary Search | [June LeetCoding Challenge] [Leetcode #222]'
Algorithms Made Easy 6 mins
Count Complete Tree Nodes | Day 23 | Binary Search | [June LeetCoding Challenge] [Leetcode #222]
YouTube video 'Count Complete Tree Nodes | Java | LeetCode - Medium -222 | The Code Mate'
The Code Mate 10 mins
Count Complete Tree Nodes | Java | LeetCode - Medium -222 | The Code Mate
YouTube video 'count complete tree nodes | count complete tree nodes leetcode | leetcode 222 | tree'
Naresh Gupta 13 mins
count complete tree nodes | count complete tree nodes leetcode | leetcode 222 | tree
YouTube video 'Daily Leetcode #84: Jun 23, 2020 - 222. Count Complete Tree Nodes'
Programming Live with Larry 22 mins
Daily Leetcode #84: Jun 23, 2020 - 222. Count Complete Tree Nodes
YouTube video 'Daily Leetcode #572: Oct 24, 2021 - 222. Count Complete Tree Nodes'
Programming Live with Larry 30 mins
Daily Leetcode #572: Oct 24, 2021 - 222. Count Complete Tree Nodes
YouTube video 'Crack the LeetCode 222. Count Complete Tree Nodes Count Nodes in Sub-Logarithmic Time in Python'
vanAmsen 7 mins
Crack the LeetCode 222. Count Complete Tree Nodes Count Nodes in Sub-Logarithmic Time in Python
YouTube video 'Leetcode | 222. Count Complete Tree Nodes | Easy | Javascript'
Software Interviews Prep 13 mins
Leetcode | 222. Count Complete Tree Nodes | Easy | Javascript
YouTube video 'LeetCode 222: Count Complete Tree Nodes | C# Solution | Binary Search in Tree |'
Code Scribbler 3 mins
LeetCode 222: Count Complete Tree Nodes | C# Solution | Binary Search in Tree |
YouTube video 'Leetcode [222] Count Complete Tree Nodes'
SDE Skills 23 mins
Leetcode [222] Count Complete Tree Nodes
YouTube video 'Leetcode 222 ||Count Complete Tree Nodes || Leetcode Daily Medium || Tree || cpp'
Komal Pal 5 mins
Leetcode 222 ||Count Complete Tree Nodes || Leetcode Daily Medium || Tree || cpp
YouTube video 'LeetCode 222 | Count Complete Tree Nodes | Java'
Sleepy Cracker 8 mins
LeetCode 222 | Count Complete Tree Nodes | Java
YouTube video 'Leetcode 222 - Count Complete Tree Nodes - Python'
Lit Code 12 mins
Leetcode 222 - Count Complete Tree Nodes - Python
YouTube video 'Day 237: LeetCode Problem 222. Count Complete Tree Nodes - Swift'
iOSxBank 12 mins
Day 237: LeetCode Problem 222. Count Complete Tree Nodes - Swift
YouTube video 'leetcode 222. Count Complete Tree Nodes - binary search'
Code-Yao 19 mins
leetcode 222. Count Complete Tree Nodes - binary search
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   September 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality