Maximum Depth of Binary Tree - Problem

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Input & Output

Example 1 — Balanced Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: 3
💡 Note: The longest path is from root 3 → 20 → 15 (or 7), which has 3 nodes, so depth is 3.
Example 2 — Linear Tree
$ Input: root = [1,null,2]
Output: 2
💡 Note: The tree has only a right path: 1 → 2, so the depth is 2.
Example 3 — Single Node
$ Input: root = [1]
Output: 1
💡 Note: Tree has only one node (the root), so the depth is 1.

Constraints

  • The number of nodes in the tree is in the range [0, 104]
  • -100 ≤ Node.val ≤ 100

Visualization

Tap to expand
Maximum Depth of Binary Tree INPUT Binary Tree Structure: 3 9 20 15 7 Input Array: [3, 9, 20, null, null, 15, 7] Depth 1 Depth 2 Depth 3 ALGORITHM STEPS Depth-First Search (Recursive) 1 Base Case Check If node is null, return 0 2 Recurse Left leftDepth = maxDepth(left) 3 Recurse Right rightDepth = maxDepth(right) 4 Return Max + 1 max(left, right) + 1 Call Stack Example: maxDepth(3) maxDepth(9) --> 1 maxDepth(20) maxDepth(15) --> 1 maxDepth(7) --> 1 --> max(1,1)+1 = 2 FINAL RESULT Longest Path Highlighted: 3 9 20 15 7 Maximum Depth 3 OK - Verified 3 nodes in longest path Key Insight: The maximum depth of a binary tree equals 1 + max(leftSubtreeDepth, rightSubtreeDepth). DFS recursively calculates depths, and the base case (null node) returns 0. Time Complexity: O(n) | Space Complexity: O(h) where h = height of tree TutorialsPoint - Maximum Depth of Binary Tree | Depth-First Search (Recursive)
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
235.8K Views
High Frequency
~15 min Avg. Time
8.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen