The two-condition part is what got me at first.
Use a post-order DFS that returns both the height and the sum of node values for each subtree. At each node, check if the height difference between left and right subtrees is ≤1 and if the total sum is even; if so, increment a counter. This single traversal achieves O(n) time and O(h) space.
Pro tip: Clarify that 'subtree' means any node and all its descendants, not just the entire tree. Also, mention that the height of a null subtree is typically -1 (or 0) and confirm the convention with the interviewer to avoid off-by-one errors.
Confirm what constitutes a subtree (any node and its descendants), how height is defined (edges vs. nodes, null height), and whether node values can be negative. This ensures alignment with the interviewer.
Define a helper that returns a pair (height, sum) for a given node. For null, return (-1, 0) or (0, 0) based on agreed convention. Recursively compute left and right results.
At each node, compute height difference and total sum. If |leftHeight - rightHeight| ≤ 1 and sum is even, increment a global counter. Return the node's height and sum to the parent.
State that the algorithm visits each node once, giving O(n) time and O(h) space for recursion stack. Discuss edge cases: empty tree, single node, skewed tree, negative values affecting parity.
Walk through a small example (e.g., a balanced tree with even sums) to verify the logic. Optionally, mention iterative post-order traversal to avoid recursion limits.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.