Maximum Depth of Binary Tree
Easy · tree dfs
You are given the root of a binary tree. Return its maximum depth: the number of nodes on the longest path that starts at the root and walks down to a leaf.
Count nodes, not edges. A tree with a single node has depth 1. An empty tree has depth 0.
Examples
Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: 3
The longest path is 3 -> 20 -> 15 (or 3 -> 20 -> 7), which touches 3 nodes.
Example 2
Input: root = [1, null, 2]
Output: 2
A lone right child still counts as a level.
Example 3
Input: root = []
Output: 0
There are no nodes at all.
Constraints
- The number of nodes is in the range [0, 1000].
- -100 <= Node.val <= 100