Sum of Nodes with Even-Valued Grandparent
MediumTreesdfs
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given the root of a binary tree, return the sum of the values of all nodes whose **grandparent** has an even value. A node's grandparent is the parent of its parent, if one exists.
Nodes without a grandparent (the root and its children) never contribute. If no node qualifies, return 0.
Examples
Input: root = [2,3,4,5,6,7,8]
Output: 26
The root 2 is even, and its grandchildren are 5, 6, 7 and 8.
Input: root = [4,1,null,6,null,3,5]
Output: 6
6 has grandparent 4 (even). 3 and 5 have grandparent 1, which is odd.
Input: root = [1]
Output: 0
A single node has no grandparent.
Constraints
- 1 <= number of nodes <= 10^4
- 1 <= Node.val <= 100
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.