I knew the general idea going in but the 'does it pass through the root' part tripped me up for a second.
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 that node is the sum of the heights of its left and right subtrees; update the global max accordingly. This handles all paths, not just those through the root, in O(n) time and O(h) space.
Pro tip: Clarify that the diameter is the number of edges, not nodes, and explicitly state that the path does not have to pass through the root. Mention that you can solve it in one pass without storing all node heights, which is more space-efficient.
Confirm that diameter is the maximum number of edges on any path between two nodes, and that the path may or may not pass through the root. State that for an empty tree the diameter is 0, and for a single-node tree it is also 0.
Use a post-order DFS (recursive or iterative) to compute the height of each subtree bottom-up. This allows you to evaluate the longest path through each node as you go.
For a node, the longest path through it is leftHeight + rightHeight (in edges). The height returned to the parent is 1 + max(leftHeight, rightHeight). Update a global maximum with the path length at each node.
Write the recursive function, initializing the global max to 0. For null nodes, return -1 (so that leaf nodes have height 0) or return 0 and adjust the path calculation accordingly. Ensure empty and single-node trees return 0.
State that the time complexity is O(n) because each node is visited once, and space complexity is O(h) for the recursion stack, where h is the tree height (O(n) worst case, O(log n) for balanced trees). Walk through a small example to verify.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.