Sum of Nodes with Even-Valued Grandparent Problem
Description
LeetCode Problem 1315.
Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0.
A grandparent of a node is the parent of its parent if it exists.
Example 1:

Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18
Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
Example 2:

Input: root = [1]
Output: 0
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]. 1 <= Node.val <= 100
Solution
Approach: Let Each Even Node Add Its Grandchildren
Instead of asking every node who its grandparent is, turn it around: an even-valued node adds the values of its grandchildren, the children of its children. Every node has at most one grandparent, so each value is added at most once, and exactly the nodes with an even-valued grandparent are counted.
Visit every node once (we use an explicit stack; any traversal works). For each child of the current node: if the current node is even, add that child's own children to the total; then push the child to visit it later.
In Example 1, the root 6 adds its grandchildren 2 + 7 + 1 + 3 = 13, and 8 adds 5, the child of its child 3. The other even nodes, 2 and 4, have no grandchildren, so the answer is 18.
Complexity: O(n) time, since every node is visited once, and O(n) space for the stack in the worst case.
class Solution:
def sumEvenGrandparent(self, root: Optional[TreeNode]) -> int:
total = 0
stack = [root]
while stack:
node = stack.pop()
for child in (node.left, node.right):
if child is None:
continue
if node.val % 2 == 0:
# An even node is the grandparent of its children's children.
for grandchild in (child.left, child.right):
if grandchild:
total += grandchild.val
stack.append(child)
return total