LeetCode 543 ·
Easy
Diameter of Binary Tree
Find the length of the longest path between any two nodes (may not pass the root).
Try it
Step through the core mechanic. The simulator below runs the tree dp shape this problem is built on.
Walk the pattern
No dedicated step-through for this one yet. The shape is Tree DP — its pattern page has the interactive walkthrough, the reference implementation, and a five-problem progression that this problem sits inside.
The approach
DFS returns each node's height; the diameter through a node is left height + right height. Track a global max as the recursion unwinds. Classic "compute up, decide at node" tree DP.
| Aspect | Value |
|---|---|
| Pattern | Tree DP |
| Recognise it by | Longest path between any two nodes. |
| Time complexity | O(n) |
| Space complexity | O(h) |
| Difficulty | Easy |
Who asks it
Companies known to ask this problem, from public LeetCode company-tag aggregations. A signal of where to expect it, not a guarantee.