Skip to problem
←

Diameter of Binary Tree

Easy 0 attempts

For a binary tree, the diameter is the length — counted in edges — of the longest path connecting any two of its nodes; this path may or may not pass through the root. Return that length.

Function contract

root is the root node of a nonempty binary tree. Test inputs use level-order arrays with null for missing children; the function receives nodes with val, left, and right properties.

Output: Return the maximum number of edges on a path between any two nodes.

Example 1

Input
root = [1,2,3,4,5]
Output
3

Example 2

Input
root = [1]
Output
0
Visual Aid
Count edges, not nodes
12345

For [1,2,3,4,5], the path 4 → 2 → 1 → 3 has 3 edges. A longest path need not pass through the root.

Constraints
  • 1 <= number of nodes <= 10^4
  • -100 <= Node.val <= 100

Iterative Postorder

Collect a parent-before-child order and process it backward. Each node contributes the sum of its two child heights to the diameter.

javascript
function diameterOfBinaryTree(root) {
  if (!root) return 0;
  const order = [],
    stack = [root];
  while (stack.length) {
    const node = stack.pop();
    order.push(node);
    if (node.left) stack.push(node.left);
    if (node.right) stack.push(node.right);
  }
  const heights = new Map();
  let diameter = 0;
  for (let i = order.length - 1; i >= 0; i--) {
    const node = order[i],
      l = heights.get(node.left) || 0,
      r = heights.get(node.right) || 0;
    diameter = Math.max(diameter, l + r);
    heights.set(node, 1 + Math.max(l, r));
  }
  return diameter;
}

Time: O(n) | Space: O(n) auxiliary space, excluding output

Loading discussion…

Saved in this browser only. Private to you.

JavaScript