Given the root of a binary tree, return its maximum depth.
The maximum depth of a binary tree is the number of nodes along the longest path from the root down to the farthest leaf. An empty tree has a depth of 0.
The trees below are written in level order (top to bottom, left to right), with None for a missing child.
Example 1:
3
/ \
9 20
/ \
15 7
Input: root = [3,9,20,None,None,15,7]
Output: 3
Explanation: The longest paths from the root to a leaf, 3 → 20 → 15 and 3 → 20 → 7, have 3 nodes each. The path 3 → 9 has only 2.
Example 2:
1
\
2
Input: root = [1,None,2]
Output: 2
Explanation: The only path, 1 → 2, has 2 nodes.
Example 3:
Input: root = [] Output: 0 Explanation: An empty tree has no nodes, so its depth is 0.
Constraints:
- The number of nodes in the tree is in the range
[0, 104]. - Each node value is between
-100and100. - The tree is at most
400levels deep.
Follow up: Can you do it in
O(n) time, visiting each of the n nodes only once?Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
