Diameter of Binary Tree

EasyBinary Tree · Post-Order DFS🧩 Tree DFSLeetCode #543 ↗Updated

Problem

Given the root of a binary tree, return the length of its longest path between any two nodes, measured in edges. The path does not have to go through the root.
Input[1,2,3,4,5]Output3 (4→2→1→3)
Input[1,2]Output1

1 ≤ n ≤ 104  ·  -100 ≤ Node.val ≤ 100

Try it yourself

Java
class Solution {
    public int diameterOfBinaryTree(TreeNode root) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Every path has a single highest node; through it the length is height(left) + height(right). A post-order pass that returns heights can update the best answer at every node for free.
PatternTree DFS

Instinct If the answer for a node can be built from the answers of its left and right subtrees, write one recursive function and trust it on the children.

Memory hack Ask the kids, then decide - each child reports up, the parent combines, and a global variable keeps the best "bend" seen so far.

Open the Tree DFS guide →

Approaches

Brute ForceHeight Recomputed at Every Node

Time O(n²)Space O(h)

For each node, compute both subtree heights from scratch and treat it as the path's top; recurse into both children and keep the max. Heights of deep nodes are recomputed by every ancestor (O(n log n) if balanced, O(n²) if skewed).

Java
public int diameterOfBinaryTree(TreeNode root) {
    if (root == null) return 0;
    int through = height(root.left) + height(root.right);
    int best = Math.max(diameterOfBinaryTree(root.left), diameterOfBinaryTree(root.right));
    return Math.max(through, best);
}
private int height(TreeNode node) { // number of nodes on the longest downward path
    if (node == null) return 0;
    return 1 + Math.max(height(node.left), height(node.right));
}

Direct translation of the definition, but repeats the same height work.

At a glance

LevelApproachTimeSpace
Brute ForceHeight Recomputed at Every NodeO(n²)O(h)
BetterMemoized Heights (HashMap)O(n)O(n)
OptimalSingle Post-Order PassO(n)O(h)
Common pitfalls
  • Returning height(left) + height(right) of the root only — the longest path may skip the root.
  • Counting nodes instead of edges (off by one).
  • Returning the diameter instead of the height to the parent — the two must stay separate.
Interview tips
  • Draw a tree whose longest path lives entirely in the left subtree.
  • Clarify the unit: edges, not nodes.
  • Explain the O(n²) → O(n) jump: compute height once and reuse it.
Pattern
Post-order DFS with a global best → “longest/best path anywhere in a tree” problems.
My notes saved in this browser