Java Binary Tree Program · OT14
Maximum Depth of a Binary Tree in Java
The depth of a tree is one more than the depth of its deeper subtree. That single sentence is the whole recursive solution.
Problem Statement
Given the root of a binary tree, return its maximum depth: the number of nodes on the longest path from the root down to a leaf.
An empty tree has depth 0 and a single node has depth 1. Trees are written in level order, with null for missing children.
Input/Output Examples
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7]Output4Explanation: the longest paths, such as 8→3→6→4, have 4 nodes.[]Output0Explanation: there are no nodes.[5]Output1Explanation: the root is also a leaf.Visual Explanation
- Leavesdepth14714each leaf returns 1
- Node 6depth61 + max(1, 1) = 2
- Node 3depth31 + max(1, 2) = 3
- Root 8depth81 + max(3, 2) = 4
- Done4
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7] bottom-up: each node returns 1 plus the larger depth of its two subtrees. The left subtree (through 3 and 6) is deeper.The recursion reaches the leaves first and combines the answers on the way back up, so every node is visited exactly once.
Approaches
Depth-first recursion is the shortest solution. Breadth-first search counts the levels instead.
Approach 1: Recursive DFS (Recommended)
Idea: the depth of a node is 1 plus the maximum depth of its children; an empty subtree has depth 0.
- If the node is
null, return 0. - Compute the depths of the left and right subtrees.
- Return
1 + max(left, right).
Time: O(n) · Space: O(h). h is the height; a skewed tree makes it O(n).
Approach 2: Level-Order BFS
Idea: process the tree one level at a time with a queue and count the levels.
- Put the root in a queue.
- While the queue is not empty, increase
depthand process exactly the nodes of the current level. - Add their children for the next level.
Time: O(n) · Space: O(w). w is the maximum width of a level.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Recursive DFS (Recommended)
The program also includes a helper that builds a tree from a level-order array, so you can try your own inputs.
public class DepthRecursive {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
// Builds a tree from level-order values, where null means "no child here"
static TreeNode build(Integer... values) {
if (values.length == 0 || values[0] == null) {
return null;
}
TreeNode root = new TreeNode(values[0]);
java.util.Queue<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < values.length) {
TreeNode node = queue.poll();
if (i < values.length && values[i] != null) {
node.left = new TreeNode(values[i]);
queue.add(node.left);
}
i++;
if (i < values.length && values[i] != null) {
node.right = new TreeNode(values[i]);
queue.add(node.right);
}
i++;
}
return root;
}
// depth(node) = 1 + the deeper of its two subtrees; an empty tree has depth 0
static int maxDepth(TreeNode node) {
if (node == null) {
return 0;
}
return 1 + Math.max(maxDepth(node.left), maxDepth(node.right));
}
public static void main(String[] args) {
System.out.println("[8, 3, 10, 1, 6, null, 14, null, null, 4, 7] -> "
+ maxDepth(build(8, 3, 10, 1, 6, null, 14, null, null, 4, 7)));
System.out.println("[] -> " + maxDepth(build()));
System.out.println("[5] -> " + maxDepth(build(5)));
}
}
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7] -> 4 [] -> 0 [5] -> 1
Time complexity: O(n) · Space complexity: O(h).
Approach 2: Level-Order BFS
No recursion, so very deep trees cannot overflow the call stack.
import java.util.ArrayDeque;
import java.util.Queue;
public class DepthLevelOrder {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
// Builds a tree from level-order values, where null means "no child here"
static TreeNode build(Integer... values) {
if (values.length == 0 || values[0] == null) {
return null;
}
TreeNode root = new TreeNode(values[0]);
java.util.Queue<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < values.length) {
TreeNode node = queue.poll();
if (i < values.length && values[i] != null) {
node.left = new TreeNode(values[i]);
queue.add(node.left);
}
i++;
if (i < values.length && values[i] != null) {
node.right = new TreeNode(values[i]);
queue.add(node.right);
}
i++;
}
return root;
}
// Counts how many levels a breadth-first traversal visits
static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
int depth = 0;
while (!queue.isEmpty()) {
depth++;
for (int size = queue.size(); size > 0; size--) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
return depth;
}
public static void main(String[] args) {
System.out.println("[8, 3, 10, 1, 6, null, 14, null, null, 4, 7] -> "
+ maxDepth(build(8, 3, 10, 1, 6, null, 14, null, null, 4, 7)));
System.out.println("[] -> " + maxDepth(build()));
System.out.println("[5] -> " + maxDepth(build(5)));
}
}
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7] -> 4 [] -> 0 [5] -> 1
Time complexity: O(n) · Space complexity: O(w).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Recursive DFS | O(n) | O(h) |
| Level-Order BFS | O(n) | O(w) |
Here n is the number of nodes. Both approaches visit every node once; DFS needs stack space for the height, BFS needs queue space for the widest level.
Interview Tips and Recommended Approach
- Agree on the definition. Some problems count edges instead of nodes; the edge-based depth is one less.
- Handle the empty tree. Returning 0 for
nullmakes the recursion work for leaves too. - Mention stack depth. A tree shaped like a linked list can make recursion very deep.
- Reuse the pattern. Balanced-tree checks and the diameter problem build on this height function.
Recommended Approach: Recursive DFS
Why: it is three lines long, visits each node once and mirrors the definition of depth exactly.