Diameter of Binary Tree (LeetCode 543): Solution and Explanation

Easy
Tree
Depth First Search
Binary Tree

The diameter of a binary tree is the number of edges on the longest path between any two nodes. That path may or may not pass through the root. Compute it.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Every path in a tree has a single highest node, the point where it turns from going up to going down. At that turning node, the path goes down into the left subtree as far as it can and down into the right subtree as far as it can. So the longest path that turns at a node has length equal to the height of its left subtree plus the height of its right subtree, measured in edges.

That gives a brute force: for every node, compute both subtree heights from scratch and take the best sum. Computing a height costs O(size of subtree), so on a skewed tree the total becomes O(n²). The waste is that the same heights are recomputed over and over by every ancestor.

The fix is to compute heights bottom up, once. A post-order DFS returns the height of each subtree to its parent. While a node has both child heights in hand, it can also evaluate the longest path that turns at itself, left + right, and update a global best. Then it returns 1 + max(left, right) so its parent can do the same.

This pattern, return one thing to the parent while updating a different global answer on the side, appears in many tree problems, such as Binary Tree Maximum Path Sum. The value a parent needs from a child (a single downward branch) is not the same as the value the problem asks for (a path that may bend).

Approach: Post-order DFS returning heights

  1. Initialize self.res = 0 to hold the best diameter found.
  2. Define dfs(curr). If curr is None, return 0.
  3. Recursively compute left = dfs(curr.left) and right = dfs(curr.right), the number of nodes on the longest downward path in each subtree.
  4. Update self.res = max(self.res, left + right), the number of edges on the longest path turning at curr.
  5. Return 1 + max(left, right) to the parent.
  6. Call dfs(root) and return self.res.

Step-by-step example

root = [1,2,3,4,5]
  1. Leaves 4 and 5 each see 0 from both children, so they leave res at 0 and return 1.
  2. Node 2 gets left = 1 and right = 1. The path 4, 2, 5 has 2 edges, so res = 2. It returns 2.
  3. Leaf 3 returns 1 and does not change res.
  4. Root 1 gets left = 2 and right = 1, so the path turning at the root has 3 edges and res = 3. It returns 3.
  5. The answer is 3, for a path such as 4, 2, 1, 3.

Code: Python, Java, C++

1class Solution:
2    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
3        self.res = 0
4        
5        def dfs(curr):
6            if not curr:
7                return 0
8            
9            left = dfs(curr.left)
10            right = dfs(curr.right)
11            
12            self.res = max(self.res, left + right)
13            return 1 + max(left, right)
14            
15        dfs(root)
16        return self.res

Time and space complexity

Time

O(n)

Each node is visited once and does constant work besides its two recursive calls.

Space

O(h)

The recursion depth equals the tree height h, which is O(n) for a skewed tree and O(log n) for a balanced one.

Other approaches

Height computed per node (time O(n²), space O(h))

For every node, call a separate height function on its two children and take the best sum. It follows the definition directly but recomputes heights repeatedly, which is quadratic on skewed trees.

Iterative post-order with a height map (time O(n), space O(n))

Traverse the tree in post-order with an explicit stack and store each node's height in a dictionary. It is useful when recursion depth is a concern on very deep trees.

Common mistakes

  • Returning the diameter from the recursion instead of the height. The parent needs a single downward branch, not a path that already bends.
  • Only checking the path through the root. The longest path often sits entirely inside one subtree.
  • Mixing up nodes and edges. Here left + right counts edges because each side counts the nodes below curr, so do not add 1 to it.
  • Using a plain local variable for the best answer inside a nested function in Python without self or nonlocal, which raises an error on assignment.

Frequently asked questions

Does the diameter always pass through the root?

No. If one subtree is much deeper and wider than the other, the longest path can be entirely inside it. That is why every node is checked as a possible turning point.

Is the diameter counted in nodes or edges?

It is counted in edges. A path through three nodes has a length of 2.

What is the time complexity of Diameter of Binary Tree?

The single-pass DFS is O(n) time and O(h) space. A naive version that recomputes heights for every node is O(n²).

How is this related to Binary Tree Maximum Path Sum?

Both use the same structure: return the best single branch to the parent and update a global answer with the best path that bends at the current node. Maximum Path Sum uses node values and ignores negative branches.