Diameter of Binary Tree Easy 0 attempts
LeetCode ↗

Diameter of Binary Tree

Easy TreeBinary TreeDFS LeetCode

Given a binary tree, find the length of the diameter — the longest path between any two nodes (measured in edges).

Example: root = [1,2,3,4,5] → Output: 3 (path: 4→2→1→3)

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

DFS with Global Max

function diameterOfBinaryTree(root) {
  let diameter = 0;
  function depth(node) {
    if (!node) return 0;
    const l = depth(node.left), r = depth(node.right);
    diameter = Math.max(diameter, l + r);
    return Math.max(l, r) + 1;
  }
  depth(root);
  return diameter;
}

Time: O(n) | Space: O(h)

Saved in this browser only. Private to you.

JavaScript