Writing the node class first was a bit of a curveball.
Start by defining a simple TreeNode class with value, left, and right attributes. Then implement a single recursive DFS that traverses the tree, computing the sum of all nodes, tracking the maximum root-to-leaf path sum, and recording the leaf node where that maximum occurs. Finally, return the results in the required order.
Pro tip: During the interview, explicitly discuss edge cases such as an empty tree, a single-node tree, and negative values, and clarify how they affect the maximum path sum and leaf identification. Also, mention that you can combine the three computations into one traversal to optimize time.
Create a class with a constructor that initializes the node's value and sets left and right children to None. Ensure it's simple and meets the 'from scratch' requirement.
Decide on a recursive depth-first search (DFS) that will visit each node exactly once. Explain that you'll pass down the current path sum and update global variables for total sum, max path sum, and the corresponding leaf.
Write a recursive function that adds the node's value to the total sum, updates the current path sum, and if the node is a leaf, compares the path sum to the current maximum and updates the max and leaf reference if needed. Then recurse on left and right children.
After traversal, handle the empty tree case by returning 0, None, or appropriate defaults. Return the total sum, maximum path sum, and the leaf node (or its value) as required.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.