Maximum Depth of Binary Tree
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.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
Sample Input
—
Sample Output
—
Constraints
- 0 <= number of nodes <= 10^4
- -100 <= Node.val <= 100
Test Cases
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
Topics
Approach: Recursive DFS
The depth of a tree is 1 plus the maximum of the depths of its left and right subtrees. Base case: a null node has depth 0.
function maximumDepthOfBinaryTree(root) {
if (!root) return 0;
return 1 + Math.max(
maximumDepthOfBinaryTree(root.left),
maximumDepthOfBinaryTree(root.right)
);
}
Time Complexity: O(n)
Space Complexity: O(h) where h is tree height
Saved in this browser only. Private to you.