Maximum Depth of Binary Tree Easy 0 attempts
LeetCode ↗

Maximum Depth of Binary Tree

Easy TreeBinary TreeDFS LeetCode

You're given the root of a binary tree. Return its maximum depth — the count of nodes along the longest path starting at the root and ending at whichever leaf is farthest away.

Input Format
Implement maximumDepthOfBinaryTree(root). Inputs below show JavaScript function arguments; there is no stdin parsing. Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 · Run Sample

Input
root = [3,9,20,null,null,15,7]
Output
3

Example 2

Input
root = [1,null,2]
Output
2

Example 3

Input
root = []
Output
0
Constraints
  • 0 <= number of nodes <= 10^4
  • -100 <= Node.val <= 100
Test Cases (3)
Case 1
Args: [[3,9,20,null,null,15,7]] Expected: 3
Case 2
Args: [[1,null,2]] Expected: 2
Case 3
Args: [[]] Expected: 0

Iterative DFS

Track each node with its depth. An explicit stack also works for a long chain without overflowing the JavaScript call stack.

javascript
function maximumDepthOfBinaryTree(root) {
  if (!root) return 0;
  const stack = [[root,1]]; let depth = 0;
  while(stack.length) {
    const [node,d] = stack.pop(); depth = Math.max(depth,d);
    if(node.left)stack.push([node.left,d+1]);
    if(node.right)stack.push([node.right,d+1]);
  }
  return depth;
}

Time: O(n) | Space: O(h) auxiliary space, excluding output

Saved in this browser only. Private to you.

JavaScript