Java Binary Tree Program · OT15
Diameter of a Binary Tree in Java
The longest path between two nodes bends at some highest node. Its length there is the height of the left subtree plus the height of the right subtree.
Problem Statement
Given the root of a binary tree, return the length of its diameter: the number of edges on the longest path between any two nodes.
The path does not have to pass through the root. A tree with one node has diameter 0.
Input/Output Examples
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7]Output5Explanation: for example 4→6→3→8→10→14 has 5 edges.[1]Output0Explanation: a path needs at least two nodes.[1, 2, null, 3, null, 4]Output3Explanation: the tree is a line of four nodes: three edges.Visual Explanation
- Node 6heightsL=1R=1path through 6 1 + 1 = 2
- Node 3heightsL=1R=2path through 3 1 + 2 = 3
- Node 10heightsL=0R=1path through 10 0 + 1 = 1
- Root 8heightsL=3R=2path through 8 3 + 2 = 5
- Done5
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7], each node's candidate path is its left height plus its right height. The best candidate, 5, passes through the root 8.Heights are counted in nodes, so the number of edges on the path through a node is exactly left height plus right height. Recording the best value while computing heights needs only one traversal.
Approaches
The one-pass DFS computes heights and the diameter together. The brute force recomputes heights for every node.
Approach 1: One-Pass DFS (Recommended)
Idea: compute each subtree's height in a post-order traversal, and update the best diameter with left + right at every node.
- Return 0 for an empty subtree.
- Get the left and right heights recursively.
- Update
best = max(best, left + right). - Return
1 + max(left, right)as this node's height.
Time: O(n) · Space: O(h).
Approach 2: Brute Force Per Node
Idea: for every node, compute both subtree heights from scratch, and take the best result over all nodes.
- Compute
height(left) + height(right)for the current node. - Recursively compute the diameter of each subtree.
- Return the largest of the three values.
Time: O(n²) · Space: O(h).
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: One-Pass DFS (Recommended)
The height function does double duty: it returns heights and records the diameter as a side effect.
public class DiameterOnePass {
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;
}
private static int best;
// One post-order pass: each node's left height + right height is a path through it
static int diameter(TreeNode root) {
best = 0;
height(root);
return best;
}
private static int height(TreeNode node) {
if (node == null) {
return 0;
}
int left = height(node.left);
int right = height(node.right);
best = Math.max(best, left + right); // edges on the path through this node
return 1 + Math.max(left, right);
}
public static void main(String[] args) {
System.out.println("[8, 3, 10, 1, 6, null, 14, null, null, 4, 7] -> "
+ diameter(build(8, 3, 10, 1, 6, null, 14, null, null, 4, 7)));
System.out.println("[1] -> " + diameter(build(1)));
System.out.println("[1, 2, null, 3, null, 4] -> " + diameter(build(1, 2, null, 3, null, 4)));
}
}
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7] -> 5 [1] -> 0 [1, 2, null, 3, null, 4] -> 3
Time complexity: O(n) · Space complexity: O(h).
Approach 2: Brute Force Per Node
Correct and easy to follow, but it recomputes the same heights many times on deep trees.
public class DiameterBrute {
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;
}
// For every node, compute both subtree heights from scratch: O(n^2) in the worst case
static int diameter(TreeNode node) {
if (node == null) {
return 0;
}
int through = height(node.left) + height(node.right);
return Math.max(through, Math.max(diameter(node.left), diameter(node.right)));
}
private static int height(TreeNode node) {
return node == null ? 0 : 1 + Math.max(height(node.left), height(node.right));
}
public static void main(String[] args) {
System.out.println("[8, 3, 10, 1, 6, null, 14, null, null, 4, 7] -> "
+ diameter(build(8, 3, 10, 1, 6, null, 14, null, null, 4, 7)));
System.out.println("[1] -> " + diameter(build(1)));
System.out.println("[1, 2, null, 3, null, 4] -> " + diameter(build(1, 2, null, 3, null, 4)));
}
}
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7] -> 5 [1] -> 0 [1, 2, null, 3, null, 4] -> 3
Time complexity: O(n²) · Space complexity: O(h).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| One-Pass DFS | O(n) | O(h) |
| Brute Force Per Node | O(n²) | O(h) |
Here n is the number of nodes and h the height. The one-pass version visits each node once; the brute force can visit each node once per ancestor.
Interview Tips and Recommended Approach
- Count edges, not nodes. Make sure the answer for a single node is 0.
- Do not assume the path uses the root. In a tree with a large left subtree, the longest path can stay inside it.
- Avoid the repeated-height trap. Calling a separate height function at every node makes it quadratic.
- Avoid static state in real code. Use a field, an array of size 1 or a small result object instead of a static variable if the method must be thread-safe.
Recommended Approach: One-Pass DFS
Why: it finds the diameter in a single traversal by reusing the heights it already computes.