Maximum Depth of Binary Tree
Maximum Depth of Binary Tree is a easy trees & bst problem solved with the recursion pattern.
The best approach, recursive dfs, runs in O(n) time and O(h) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from level order (bfs) up.
Problem
Return the maximum depth of a binary tree: the number of nodes on the longest path from the root down to a leaf.
Examples
Example 1
- Input
root = [3, 9, 20, null, null, 15, 7]- Output
3
Example 2
- Input
root = [1, null, 2]- Output
2
Constraints
- The tree has
0to10^4nodes.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Level order (BFS) | O(n) | O(w) |
| Recursive DFS | O(n) | O(h) |
1Level order (BFS)
O(n)O(w)w = maximum width of the tree.Count the number of levels with a queue.
- Process the queue level by level; depth++ per level.
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
int depth = 0;
while (!q.isEmpty()) {
depth++;
for (int i = q.size(); i > 0; i--) {
TreeNode n = q.poll();
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
}
return depth;
}
}class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
q = deque([root])
depth = 0
while q:
depth += 1
for _ in range(len(q)):
n = q.popleft()
if n.left is not None:
q.append(n.left)
if n.right is not None:
q.append(n.right)
return depthclass Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
queue<TreeNode*> q;
q.push(root);
int depth = 0;
while (!q.empty()) {
depth++;
for (int i = q.size(); i > 0; i--) {
TreeNode* n = q.front(); q.pop();
if (n->left != nullptr) q.push(n->left);
if (n->right != nullptr) q.push(n->right);
}
}
return depth;
}
};function maxDepth(root) {
if (root === null) return 0;
let q = [root];
let depth = 0;
while (q.length > 0) {
depth++;
const next = [];
for (const n of q) {
if (n.left !== null) next.push(n.left);
if (n.right !== null) next.push(n.right);
}
q = next;
}
return depth;
}2Recursive DFS
O(n)O(h)An empty tree has depth 0. Any other node is one deeper than the deeper of its two subtrees.
- if root == null return 0.
- return 1 + max(maxDepth(left), maxDepth(right)).
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};function maxDepth(root) {
if (root === null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}Edge cases to test
- Empty tree (0)
- Skewed tree (depth n)
Hints
Hint 1
depth(node) = 1 + max(depth(left), depth(right)).
FAQ
What is the best time complexity for Maximum Depth of Binary Tree?
Recursive DFS runs in O(n) time and O(h) extra space.
Which pattern does Maximum Depth of Binary Tree use?
It is a trees & bst problem that uses the recursion pattern. Other problems with the same pattern: Binary Tree Inorder Traversal (Recursive), Binary Tree Preorder Traversal (Recursive), Binary Tree Postorder Traversal (Recursive).
Is there a brute force solution for Maximum Depth of Binary Tree?
Yes. Level order (BFS) takes O(n) time and O(w) space. Count the number of levels with a queue.
Which edge cases should I test for Maximum Depth of Binary Tree?
Empty tree (0); Skewed tree (depth n).