Leetcode #1315: Sum of Nodes with Even-Valued Grandparent
In this guide, we solve Leetcode #1315 Sum of Nodes with Even-Valued Grandparent in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Intuition
We need to explore a structure deeply before backing up, which suits DFS.
DFS keeps local context on the call stack and is easy to implement recursively.
Approach
Define a recursive DFS that carries the necessary state.
Combine child results as the recursion unwinds.
Steps:
- Define a recursive DFS with state.
- Visit children and combine results.
- Return the final aggregation.
Example
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.
Python Solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
def dfs(root: TreeNode, x: int) -> int:
if root is None:
return 0
ans = dfs(root.left, root.val) + dfs(root.right, root.val)
if x % 2 == 0:
if root.left:
ans += root.left.val
if root.right:
ans += root.right.val
return ans
return dfs(root, 1)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.