The two conditions together is what got me.
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 absolute height difference is ≤1 and the sum is even, incrementing a counter if both conditions hold. Return the height and sum upward to enable O(n) time complexity.
Pro tip: Clarify the definition of height (edges vs. nodes) and whether a single node counts as a subtree; handling these edge cases upfront shows attention to detail and avoids off-by-one errors.
Ask the interviewer to confirm the definition of height (number of edges or nodes) and whether a leaf node is considered a valid subtree. Also discuss the expected input size to determine if recursion depth is a concern.
Define a helper function that takes a node and returns a pair: the height of the subtree rooted at that node and the sum of all node values in that subtree. For a null node, return height -1 (if edges) or 0 (if nodes) and sum 0.
Recursively call the helper on the left and right children. Compute the current height as 1 + max(leftHeight, rightHeight) and the current sum as node.val + leftSum + rightSum. Check if abs(leftHeight - rightHeight) ≤ 1 and current sum is even; if so, increment a global counter.
Return the computed height and sum to the parent call. After the recursion completes, the global counter holds the total number of valid subtrees.
State that the algorithm runs in O(n) time and O(h) space due to recursion, where n is the number of nodes and h is the tree height. Walk through a small example to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.