Blind 75
26 / 75Free practice

Maximum Depth of Binary Tree

Easy · Trees

Jump to code

Find the number of nodes on the longest path from a binary tree’s root down to a leaf. An empty tree has depth zero.

Examples

Example 1

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

Output: 3

Example 2

root = [1,null,2]

Output: 2

Constraints

  • 0 <= The number of nodes in the tree <= 100
  • -100 <= Node.val <= 100

Function contract

Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.

Need a hint?

A node adds one level above its deepest child.

Asked in real interviews

Candidates reported versions of Maximum Depth of Binary Tree from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 6 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    3,
    9,
    20,
    null,
    null,
    15,
    7
  ]
]
Expected
3
Case 2
Input
[
  [
    1,
    null,
    2
  ]
]
Expected
2
Case 3
Input
[
  []
]
Expected
0
Case 4
Input
[
  [
    1
  ]
]
Expected
1
Case 5
Input
[
  [
    1,
    2,
    null,
    3
  ]
]
Expected
3

Drafts are saved per language in this browser when storage is available.