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)
Difficulty
and has an acceptance rate of about 73% (1+ million submissions).
Typical patterns to solve this problem:
- Binary Search
- Binary Tree
- Bit Manipulation
- Tree
AI Disclaimer
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.
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 rootguard returns0, 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, yielding0 + 0. The final result is1, 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 rootat 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 270: Closest Binary Search Tree Value
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 404: Sum of Left Leaves
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 79: Word Search
- problem 81: Search in Rotated Sorted Array II
- problem 97: Interleaving String
- problem 99: Recover Binary Search Tree
- problem 173: Binary Search Tree Iterator
- problem 199: Binary Tree Right Side View
- problem 230: Kth Smallest Element in a BST
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 508: Most Frequent Subtree Sum
- problem 513: Find Bottom Left Tree Value
- problem 538: Convert BST to Greater Tree
- problem 65: Valid Number
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
- problem 127: Word Ladder
Extra
- 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