Skip to main content
Back to ChallengesMaximum Depth of Binary TreeEasy 15 min

Maximum Depth of Binary Tree

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.

Examples

Input: root = [3,9,20,null,null,15,7]
Output: 3
The longest path is 3→20→15 or 3→20→7, length 3.
Input: root = [1,null,2]
Output: 2
Path is 1→2.

Constraints

  • Number of nodes in [0, 10^4]
  • -100 <= Node.val <= 100

Complexity Analysis

Time
O(n)
visit every node once.
Space
O(h)
recursion stack, O(log n) balanced, O(n) skewed.

Test Cases

#1 Standard tree
Input: [3,9,20,null,null,15,7]
Expected: 3
#2 Right-skewed
Input: [1,null,2]
Expected: 2
#3 Empty tree
Input: []
Expected: 0
#4 Single node
Input: [1]
Expected: 1
#5 Perfect binary tree
Input: [1,2,3,4,5,6,7]
Expected: 3
JavaScript
Output
Click "Run Code" to see output here...