I knew the trick was that the diameter doesn't have to pass through the root, which I almost forgot until I started drawing it out.
Clarify that the diameter is the number of edges on the longest path between any two nodes, which may or may not pass through the root. Then propose a post-order DFS that computes each node's height while tracking the maximum left-height + right-height seen so far, yielding O(n) time and O(h) space.
Pro tip: Mention that the diameter path doesn't have to pass through the root—many candidates assume it does and fail edge cases. Also note that if the problem defines diameter as node count instead of edge count, the answer differs by one, so confirm the definition upfront.
Confirm whether diameter is measured in edges or nodes, and ask about tree size, balance, and whether the tree can be empty or a single node. This shows you think about edge cases before coding.
Briefly describe the naive O(n^2) approach: for each node, compute left and right heights and take the max. This demonstrates you can reason from first principles before optimizing.
Explain that a single DFS can return each subtree's height to its parent while updating a global maximum with leftHeight + rightHeight at each node. Emphasize that the diameter through a node is the sum of its children's heights.
Trace the algorithm on a small tree (e.g., a root with two deep subtrees) to show how the global maximum is updated and why the path need not pass through the root.
Conclude with O(n) time and O(h) space (O(n) worst case for skewed trees), and mention handling of empty tree, single node, and skewed trees.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.