Diameter of Binary Tree

Difficulty: Easy

You're given the root of a binary tree. Return its diameter: the number of edges on the longest path between any two nodes. The path doesn't have to pass through the root.

Count edges, not nodes.

Examples

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

The longest path is 4 -> 2 -> 1 -> 3 (or 5 -> 2 -> 1 -> 3), which has 3 edges.

Input: root = [1,2]
Output: 1

The only path is 1 -> 2, a single edge.

Input: root = [1]
Output: 0

A single node has no path at all.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].

  • -100 <= Node.val <= 100

Approach

The longest path doesn't have to run through the root; it can sit entirely inside one subtree. For any node, the longest path through it is its left subtree height plus its right subtree height. The answer is the maximum of that over every node.

Don't recompute heights over and over. Compute them in one recursive pass, and update a running "best diameter" at each node using the heights you just calculated.

Solutions

Brute Force — Height From Every Node

For each node, compute both subtree heights with separate recursive calls and add them. This recomputes the same heights many times.

class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function height(node) {
  if (node === null) return 0;
  return 1 + Math.max(height(node.left), height(node.right));
}

function diameterOfBinaryTree(root) {
  if (root === null) return 0;

  const throughRoot = height(root.left) + height(root.right);
  const bestInLeft = diameterOfBinaryTree(root.left);
  const bestInRight = diameterOfBinaryTree(root.right);

  return Math.max(throughRoot, bestInLeft, bestInRight);
}

Time: O(n²) — height() is called on overlapping subtrees repeatedly · Space: O(h) — recursion stack depth

Optimal — Height + Diameter in One Pass

A helper returns a subtree's height and, along the way, updates a shared 'best diameter' using the current node's two child heights.

function diameterOfBinaryTree(root) {
  let best = 0;

  function height(node) {
    if (node === null) return 0;

    const leftHeight = height(node.left);
    const rightHeight = height(node.right);

    best = Math.max(best, leftHeight + rightHeight);

    return 1 + Math.max(leftHeight, rightHeight);
  }

  height(root);
  return best;
}

Time: O(n) · Space: O(h) — recursion stack depth, where h is the tree's height (O(n) worst case)