← DSA
EASY

Diameter of Binary Tree

PracticeNeetCode ↗LeetCode ↗

Given the root of a binary tree, return the length, in edges, of the longest path between any two nodes. That path doesn't need to pass through the root.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Keep a variable diameter = 0 outside the recursion.
  2. Define a height(node) helper; base case None returns 0.
  3. Recursively get the left height and right height of the node's children.
  4. Update diameter = max(diameter, left + right).
  5. Return 1 + max(left, right) as this node's own height, and call height(root) once at the end to return diameter.

Complexity

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

Code

def diameterOfBinaryTree(root: TreeNode | None) -> int:
    diameter = 0

    def height(node: TreeNode | None) -> int:
        nonlocal diameter
        if not node:
            return 0
        left = height(node.left)
        right = height(node.right)
        diameter = max(diameter, left + right)
        return 1 + max(left, right)

    height(root)
    return diameter

Code Explanation

How the solution above works, piece by piece.

  1. height(node) returns the number of nodes on the longest downward path from node (0 for an empty child).
  2. For each node, left + right is the number of edges in the longest path that bends at that node.
  3. diameter keeps the best of those over all nodes; nonlocal lets the inner function update it.
  4. Return 1 + max(left, right) to the parent: a path can only continue upward through one side.
  5. One pass: O(n) time, O(height) stack.

Visual Walkthrough

Running it on root = [1, 2, 3, 4, 5]:

Tree 1 2 3 4 5 with heights and the longest path1234532111badge = height returnedat 2: left 1 + right 1 = 2at 1: left 2 + right 1 = 3 ← bestpath 4 → 2 → 1 → 3 (3 edges)
The longest path through a node uses its left height plus its right height (in edges). Checking that at every node finds the best path even if it doesn't pass through the root; here it does: 4 → 2 → 1 → 3.
longest path

Video Explanation

NeetCode — Diameter of Binary Tree, LeetCode 543