C++ 0104.cpp
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root)
return 0;
int l = 1 + maxDepth(root->left);
int r = 1 + maxDepth(root->right);
return l < r ? r : l;
}
};
Difficulty
and has an acceptance rate of about 78% (6+ million submissions).
Typical patterns to solve this problem:
- Binary Tree
- Breadth First Search
- Depth First Search
- 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 public member function maxDepth. The function computes the maximum depth (or height) of a binary tree whose nodes are represented by the TreeNode structure. It follows a classic depth-first recursive strategy: for each node it determines the depth of its left and right subtrees, adds one to account for the current node, and returns the larger of the two results. The recursion terminates when a null pointer is encountered, which corresponds to an empty subtree.
Key Steps
Base-case handling
The first conditional checks whether the current node pointer is null. If it is, the function returns 0, indicating that an empty subtree contributes no depth.
if (!root)
return 0;
This guard prevents further dereferencing of a null pointer and serves as the termination condition for the recursion.
Recursive depth calculation
For a non-null node, the function recursively invokes itself on the left child and on the right child. Each recursive call returns the depth of the respective subtree. The returned values are incremented by one to include the current node in the depth count.
int l = 1 + maxDepth(root->left);
int r = 1 + maxDepth(root->right);
The variables l and r hold the depths of the left and right subtrees, respectively, after accounting for the current node.
Selecting the larger depth
The final step compares the two subtree depths and returns the larger one. The ternary operator is used for a concise conditional expression.
return l < r ? r : l;
If the left depth is smaller than the right depth, the right depth is returned; otherwise, the left depth is returned. This yields the maximum depth of the tree rooted at the current node.
Edge Cases Handled
When the input tree is empty (root is nullptr), the base case returns 0, correctly representing a depth of zero. For a tree consisting of a single node, the recursive calls on both children hit the base case, each returning 0. Adding one yields depths of 1 for both sides, and the comparison returns 1, which is the correct depth for a single-node tree.
In highly unbalanced trees-such as a completely left-skewed or right-skewed structure-the recursion proceeds down the longer branch, accumulating a depth count equal to the number of nodes along that path. The base case at the leaf’s null child terminates the recursion, ensuring that the depth reflects the longest root-to-leaf path.
Performance Optimizations
The implementation avoids unnecessary temporary objects by using plain integer variables for the left and right depths. The direct addition of 1 to the recursive results eliminates the need for a separate increment step after the recursion returns.
The ternary operator for selecting the maximum depth is a compile-time construct that typically translates to a single conditional branch without the overhead of a function call. This keeps the inner loop of the recursion lightweight.
Because the algorithm visits each node exactly once, the total work performed is proportional to the number of nodes in the tree. The recursion depth matches the height of the tree, which means the call stack grows only as deep as necessary, without allocating additional data structures such as explicit stacks or queues. This implicit stack usage is the most space-efficient approach for a depth-first traversal in a recursive style.
ELI5 - Simplified Explanation
Imagine this code is like finding the tallest path in a giant treehouse. The treehouse has branches that go left and right, and each branch might have more branches attached to it.
The code starts by looking at the very top of the tree. If there is nothing there, it knows the height is zero. If there is a branch, it sends a tiny explorer down the left side and another explorer down the right side.
Each explorer keeps a count of every branch they pass. The explorer on the left counts all the branches in their direction, and the explorer on the right does the same. Once they reach the very end of their paths, they check their totals. The code just looks at both numbers, picks whichever one is bigger, and says that is how deep the tree goes. It is like measuring to see which side of the treehouse is taller so you can hang your longest swing.
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 | Rust | JS | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | AdelDaniel | Dart | ||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Rust | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| Krazune | C | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | TS | ||||||||||
| MacJim | C++ | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | Java | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C, C++, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| AdelDaniel | Dart | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Rust | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| Krazune | C | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++, TypeScript | |||||||||||
| MacJim | C++ | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | Java | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 662: Maximum Width of Binary Tree
- problem 1376: Time Needed to Inform All Employees
- problem 2385: Amount of Time for Binary Tree to Be Infected
- problem 2458: Height of Binary Tree After Subtree Removal Queries
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
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