Problem 104

Abstract / Summary

Find the greatest number of levels in a tree that starts at the root and goes down to the farthest leaf.

Note

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

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;
    }
};
11 lines | 237 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

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
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.35 | σ = 0.78

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 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++
62 links | 44 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Maximum Depth of Binary Tree - Leetcode 104 - Trees (Python)'
Greg Hogg 6 mins
Maximum Depth of Binary Tree - Leetcode 104 - Trees (Python)
YouTube video 'Maximum Depth of Binary Tree - LeetCode 104 - Python'
Deepti Talesra 8 mins
Maximum Depth of Binary Tree - LeetCode 104 - Python
YouTube video 'LeetCode 104. Maximum Depth of Binary Tree - Interview Prep Ep 65'
Fisher Coder 15 mins
LeetCode 104. Maximum Depth of Binary Tree - Interview Prep Ep 65
YouTube video 'Maximum Depth of Binary Tree | Leetcode - 104'
Algorithms Made Easy 3 mins
Maximum Depth of Binary Tree | Leetcode - 104
YouTube video 'Maximum Depth of Binary Tree - LeetCode 104 - JavaScript'
AlgoJS 9 mins
Maximum Depth of Binary Tree - LeetCode 104 - JavaScript
YouTube video 'Maximum Depth of Binary Tree | Leetcode 104 | Day 14 | Leetcode Feb Challenge'
Ayushi Sharma 9 mins
Maximum Depth of Binary Tree | Leetcode 104 | Day 14 | Leetcode Feb Challenge
YouTube video 'Maximum Depth of Binary Tree | Leet code 104 | Theory explained + Python code'
Sai Anish Malla 10 mins
Maximum Depth of Binary Tree | Leet code 104 | Theory explained + Python code
YouTube video '104. Maximum Depth of Binary Tree Java Solution'
Code with Carter 7 mins
104. Maximum Depth of Binary Tree Java Solution
YouTube video 'Maximum Depth of Binary Tree | Leetcode 104 | Height of Binary Tree #dsa'
Learn With Chirag 7 mins
Maximum Depth of Binary Tree | Leetcode 104 | Height of Binary Tree #dsa
YouTube video 'Maximum Depth of Binary Tree - LeetCode 104 - LeetCode Daily Challenge'
One Code Man 4 mins
Maximum Depth of Binary Tree - LeetCode 104 - LeetCode Daily Challenge
YouTube video '104. Maximum Depth of Binary Tree | JavaScript | DFS | O(n) TC | LeetCode Daily Challenge'
LeetCodeWithMonu 8 mins
104. Maximum Depth of Binary Tree | JavaScript | DFS | O(n) TC | LeetCode Daily Challenge
YouTube video 'LeetCode 104: Maximum Depth of Binary Tree [Python]'
Frederik Müller 8 mins
LeetCode 104: Maximum Depth of Binary Tree [Python]
YouTube video 'Maximum Depth of Binary Tree || Binary Tree 4 || Placement Preparation Series || LeetCode 104 ||'
Bro Coders 11 mins
Maximum Depth of Binary Tree || Binary Tree 4 || Placement Preparation Series || LeetCode 104 ||
YouTube video 'Maximum Depth of Binary Tree in Telugu | DFS, BFS Python Approaches | Leetcode 104 | srkcodes'
Srk Codes 9 mins
Maximum Depth of Binary Tree in Telugu | DFS, BFS Python Approaches | Leetcode 104 | srkcodes
YouTube video 'Maximum Depth of Binary Tree | maximum depth of binary tree | leetcode 104 dfs bfs'
Naresh Gupta 6 mins
Maximum Depth of Binary Tree | maximum depth of binary tree | leetcode 104 dfs bfs
YouTube video 'LeetCode 104: Maximum Depth of Binary Tree | C# Solution | BFS & DFS Approaches |'
Code Scribbler 6 mins
LeetCode 104: Maximum Depth of Binary Tree | C# Solution | BFS & DFS Approaches |
YouTube video 'How To Solve "104  Maximum Depth of Binary Tree" on LeetCode - JavaScript Easy'
Becoming A Better Dev (with David) 4 mins
How To Solve "104 Maximum Depth of Binary Tree" on LeetCode - JavaScript Easy
YouTube video 'Maximum Depth of Binary Tree | Leetcode 104 | Live coding session | Day 1 December Challenge'
Coding Decoded 5 mins
Maximum Depth of Binary Tree | Leetcode 104 | Live coding session | Day 1 December Challenge
YouTube video 'Maximum Depth of Binary Tree - LeetCode #104 - C++'
Sean Chuah 4 mins
Maximum Depth of Binary Tree - LeetCode #104 - C++
YouTube video 'Daily Leetcode #245: Dec 01, 2020 - 104. Maximum Depth of Binary Tree'
Programming Live with Larry 6 mins
Daily Leetcode #245: Dec 01, 2020 - 104. Maximum Depth of Binary Tree
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

7 similar problems

Solved On The Same Day

18 easy 43 medium 2 hard
64 solutions   August 8, 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