Maximum Depth of Binary Tree in Java: Explanation & Practice
Find the maximum depth (height) of a binary tree
Problem summary
Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from root to a leaf.
Starter code
public class Main {
public static void main(String[] args) {
// Tree: 3
// / \
// 9 20
// / \
// 15 7
// Print: Depth: 3
}
}Expected output and test cases
- [3,9,20,null,null,15,7]
Depth: 3
- [1,null,2]
Depth: 2
- [] → 0
Depth: 0
Hints
- Base case: null node has depth 0
- Recursive: 1 + max(depth(left), depth(right))
- Can also use BFS level-by-level counting
- Each recursion adds 1 to the depth
Related Data Structures & Algorithms exercises
- Practice Min Stack in Java
- Practice Binary Tree Inorder Traversal in Java
- Practice Binary Tree Level Order Traversal in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler