Maximum Depth of Binary Tree

EasyMathLinked ListTreeBinary TreeGraph

Description

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
Explanation:

The longest path is root(3) -> right(20) -> left(15) or right(7), counting 3 nodes. The left subtree with just node 9 has depth 2, so the maximum is 3.

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

The tree has root node 1 with only a right child 2. The longest path is root(1) -> right(2), which is 2 nodes deep.

Input:root = []
Output:0
Explanation:

With no nodes in the tree (null root), there is no path to any leaf. By definition, the maximum depth of an empty tree is 0.

Constraints

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

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!