The tricky part is that the longest path doesn't have to go through the root, which is what kills most people.
Use a post-order DFS that returns the height of each subtree while updating a global maximum diameter. At each node, the longest path through it is the sum of the heights of its left and right subtrees, so update the diameter with that sum and return 1 + max(left, right).
Pro tip: Clarify that the diameter is measured in edges, not nodes, and mention that the longest path may not pass through the root. Also, note that the algorithm runs in O(n) time and O(h) space, which is optimal.
Confirm that the diameter is the number of edges on the longest path between any two nodes, and that the path may or may not pass through the root.
Use a post-order DFS (or recursion) to compute subtree heights bottom-up, because the diameter at a node depends on the heights of its left and right subtrees.
Write a helper that returns the height of the current subtree (in edges) and updates a global maximum diameter with leftHeight + rightHeight at each node.
Account for an empty tree (diameter 0), a single node (diameter 0), and skewed trees where the longest path may be entirely in one subtree.
State that the time complexity is O(n) because each node is visited once, and space complexity is O(h) due to recursion stack, where h is the tree height.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.