Coding problem · Easy · Trees
Maximum Depth of Binary Tree
Easy Algorithms & data structures Seen at Amazon, LinkedIn, Uber
Given the root of a binary tree, return its maximum depth — the number of nodes along the longest path from the root down to the farthest leaf. Trees are shown in level order with null for missing children.
Example 1
Input: root = [3,9,20,null,null,15,7] Output: 3
Example 2
Input: root = [1,null,2] Output: 2
Hints
Hint 1
depth(node) = 1 + max(depth(left), depth(right)); an empty tree has depth 0.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(h) recursion depth
Recursive DFS returns 1 + max(left, right). For very deep (skewed) trees, an iterative BFS counting levels avoids stack overflow.
Reference solution
function maxDepth(root) {
if (!root) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
function maxDepth(root: TreeNode | null): number {
return root ? 1 + Math.max(maxDepth(root.left), maxDepth(root.right)) : 0;
}
def max_depth(root: Optional[TreeNode]) -> int:
if root is None:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))
<?php
function maxDepth(?TreeNode $root): int
{
return $root === null ? 0 : 1 + max(maxDepth($root->left), maxDepth($root->right));
}
class Solution {
public int maxDepth(TreeNode root) {
return root == null ? 0 : 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
More Trees problems
- Invert Binary Tree · Easy
- Binary Tree Level Order Traversal · Medium
- Validate Binary Search Tree · Medium
- Lowest Common Ancestor of a BST · Medium