Diameter of Binary Tree

Free with account Updated Nov 19, 2026 · 5 min read
On this page

    Problem statement

    Given the root of a binary tree, return the length of its diameter: the number of edges on the longest path between any two nodes. The path may or may not pass through the root. An empty tree or a single node has diameter 0.

    A short tree problem that checks one idea: a function can return one value to its parent (the height) while updating a different answer on the side (the best path). The same pattern solves Binary Tree Maximum Path Sum and several other "longest path in a tree" questions. Original problem: LeetCode 543.

    Example

    The longest path runs from 9 up to node 2 and down to 10: six edges. It never touches the root.
    The longest path runs from 9 up to node 2 and down to 10: six edges. It never touches the root.
    Input:  root = [1, 2, 3, 4, 5, null, null, 7, null, null, 8, 9, null, null, 10]
    Output: 6          # 9 - 7 - 4 - 2 - 5 - 8 - 10
    Input:  root = [1, 2, 3]
    Output: 2          # 2 - 1 - 3

    Constraints (assumed)

    • 0 ≤ number of nodes ≤ 10⁴.
    • The tree may be very unbalanced (depth up to 10⁴).

    What this question tests

    • Seeing that every path has one highest node where it bends, so you can check every node as the bend.
    • A post-order DFS that returns one thing (height) and records another (best L + R).
    • Being exact about edges vs nodes.

    Questions to ask first

    1. Length in edges or in nodes? (Here: edges; the node count is one more.)
    2. Does the path have to go through the root? (Here: no.)
    3. What should an empty tree return? (Here: 0.)
    4. How deep can the tree be? Deep trees can overflow the call stack in recursive code.