Diameter of Binary Tree
Find the number of edges on the longest path between any two nodes of a binary tree.
Given the root of a binary tree, return its diameter: the number of edges on the longest path between any two nodes. A path follows the links between parents and children and visits each node at most once. It does not have to pass through the root.
Example 1
Output: 3
Explanation: 4 ā 2 ā 1 ā 3 (or 5 ā 2 ā 1 ā 3).
Example 2
Output: 1
The Idea
Draw Example 1 on paper, one row at a time: 1 in the first row, 2 and 3 in the second, 4 and 5 in the third. Node 1 sits at the top, as the root. Its children are 2 and 3, and 2 has two children of its own, 4 and 5. Each line from a parent to a child is an edge.
Walking from 4 to 3 means going up from 4 to 2, up again to 1, then down to 3. That walk crosses three edges. No two nodes in this tree are farther apart, so the diameter is 3.
On that walk, 1 is the highest node: the path climbs up to it and then goes down the other side. Every path has such a highest node where it turns. On the short path from 2 down to 4, the highest node is 2 itself.
So does the longest path always turn at the root? Look at the picture below. It draws the tree [1, 2, null, 3, 4, 5, null, null, 6]null
The orange path 5, 3, 2, 4, 6 crosses four edges, and its highest node is 2, not the root. The box labelled "longest path from root 1" shows the best a path from the root can do here: 1, 2, 3, 5, three edges. The longest path can turn at any node, so every node has to be checked.
How long is the longest path that turns at one node? It goes down as far as it can on the left side, and as far as it can on the right side. Node 3, together with everything below it, is the left subtree of 2. Nodes 4 and 6 form its right subtree.
Count the nodes on the longest way down a subtree, and you get its height. In the picture, "left height 2" counts nodes 3 and 5, and "right height 2" counts nodes 4 and 6. Going from 2 down to 5 crosses exactly 2 edges, one per node, so the path that turns at 2 has 2 + 2 = 4 edges.
So the diameter is the largest value of left height plus right height, taken over all the nodes. And heights are easy to build from the bottom up: a node's height is one more than the taller of its two subtrees. One walk over the tree can produce every height and every sum.
Solution Approach
Turning that idea into code means seeing why working out each node's two heights separately is slow, then settling three things: the order in which nodes are visited, how a height is counted, and where the longest path found so far is kept.
Working out each height separately
Why not work out the two heights of each node separately? A method that walks a subtree and returns its height is short to write. But calling it afresh at every node walks the lower nodes again and again. In a tree shaped like one long chain of n nodes, that adds up to about n²/2 steps.
Visiting children before their parent
How can each height be worked out only once? Ask the children first. A recursive method height(node)
Counting height in nodes
Why count nodes rather than edges? A missing child, null
In Example 2, node 1 has the left child 2 and no right child. The path that turns at 1 has 1 + 0 = 1 edge, which is the expected output.
Keeping the longest path in a field
Where does the answer go? heightbestheight
Java Solution
The method diameterOfBinaryTree
- First, set the field
back to 0, so a second call on the same object does not start from the first call's answer. Then callbest , which walks the whole tree.height(root) - Inside
, aheight node returns 0, since an empty subtree has no nodes.null - For a real node, call
onheight and onnode.left first, and keep the results innode.right andleft .right - The path that turns at this node has
edges. If that beatsleft + right , it becomes the newbest .best - Return
, the node's own height, so its parent can use it.1 + Math.max(left, right) - Once
has returned, every node has been checked, andheight(root) returnsdiameterOfBinaryTree as the diameter.best
The class also has a small TreeNodebuildmain
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
public class DiameterOfBinaryTree {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
private int best = 0;
public int diameterOfBinaryTree(TreeNode root) {
best = 0;
height(root);
return best;
}
// Returns the height in nodes and records the longest path that turns at each node.
private 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 of the path that turns at this node
return 1 + Math.max(left, right);
}
// Builds a tree from the row-by-row form, with null for a missing child.
static TreeNode build(Integer[] values) {
if (values.length == 0 || values[0] == null) {
return null;
}
TreeNode root = new TreeNode(values[0]);
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
int i = 1;
while (i < values.length) {
TreeNode parent = queue.poll();
if (values[i] != null) {
parent.left = new TreeNode(values[i]);
queue.add(parent.left);
}
i++;
if (i < values.length && values[i] != null) {
parent.right = new TreeNode(values[i]);
queue.add(parent.right);
}
i++;
}
return root;
}
public static void main(String[] args) {
DiameterOfBinaryTree solver = new DiameterOfBinaryTree();
Integer[][] trees = {
{1, 2, 3, 4, 5},
{1, 2},
{1, 2, null, 3, 4, 5, null, null, 6},
{1},
{},
{1, 2, null, 3, null, 4}
};
for (Integer[] tree : trees) {
int d = solver.diameterOfBinaryTree(build(tree));
System.out.println(Arrays.toString(tree) + " -> " + d);
}
}
}
Running it prints:
[1, 2, 3, 4, 5] -> 3
[1, 2] -> 1
[1, 2, null, 3, 4, 5, null, null, 6] -> 4
[1] -> 0
[] -> 0
[1, 2, null, 3, null, 4] -> 3
Example 1 gives 3 and Example 2 gives 1, as expected. Look at the third line: the tree from the picture gives 4, the path 5, 3, 2, 4, 6 that turns at node 2. A separate check that adds the two heights only at the root returns 3 for this same tree, so it misses the longest path.
The single node [1][]height(null)
Complexity
The work is one call of height
- Time: O(n), because
runs once for each of the n nodes and once for eachheight child, and each call does a fixed amount of work around its two recursive calls.null - Space: O(h), where h is the height of the whole tree, because the recursion keeps one open call for each node between the root and the node being visited; a chain like the last test makes h equal to n.
Weighting the path by node values instead of counting edges gives