Sum of Nodes with Even-Valued Grandparent (LeetCode 1315): Solution and Explanation

Medium
Tree
Depth First Search
Breadth First Search
Binary Tree

Add up the values of all nodes whose grandparent, the node two levels above, holds an even value.

Intuition

Looking down from an even node at its four possible grandchildren works, but it means reaching two levels down and checking for missing nodes at each step.

It is simpler to flip the view: let every node look up. A node counts when the value two levels above it is even, so each call only needs to know that one number.

Pass two values into each recursive call: the parent's value and the grandparent's value. A child call receives the current node as its parent and the current parent as its grandparent, so the window slides down one level per call.

Approach: DFS with a sliding parent and grandparent

  1. Define dfs(node, parent, grand) that returns the answer for the subtree under node.
  2. Return 0 for a null node.
  3. Start total at node.val if grand is even, otherwise at 0.
  4. Add dfs(node.left, node.val, parent) and dfs(node.right, node.val, parent), then return total.
  5. Call dfs(root, 1, 1), using the odd value 1 as a placeholder for the missing ancestors.

Step-by-step example

root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
  1. 6, 7 and 8 have no real grandparent or only the placeholder, so none of them count.
  2. The children of 7 are 2 and 7. Their grandparent is 6, which is even, so add 2 and 7. Sum = 9.
  3. The children of 8 are 1 and 3, also grandchildren of 6, so add them. Sum = 13.
  4. 9, 1 and 4 hang under 2 and 7, whose parent is 7, an odd grandparent, so they are skipped.
  5. 5 hangs under 3, whose parent is 8. Grandparent 8 is even, so add 5. Sum = 18.

Code: Python, Java, C++

1class Solution:
2    def sumEvenGrandparent(self, root: Optional[TreeNode]) -> int:
3        def dfs(node, parent, grand):
4            if not node:
5                return 0
6            total = node.val if grand % 2 == 0 else 0
7            total += dfs(node.left, node.val, parent)
8            total += dfs(node.right, node.val, parent)
9            return total
10
11        return dfs(root, 1, 1)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every node is visited once and does constant work.

Space

O(h)

The recursion stack holds one frame per level of the current path, up to the tree height h.

Other approaches

Look down from even nodes (time O(n), space O(h))

At every even node, add the values of its grandchildren by checking left.left, left.right, right.left and right.right. Same complexity with more null checks.

BFS with parent pointers (time O(n), space O(n))

Walk level by level and store each node's parent in a map. For each node, look up the parent's parent and test its value.

Common mistakes

  • Checking the parent's value instead of the grandparent's.
  • Using 0 as the placeholder for missing ancestors. 0 is even, so the root's children and grandchildren would be counted by mistake.
  • Passing the arguments in the wrong order, so the grandparent never shifts down a level.

Frequently asked questions

Why start with 1 for parent and grandparent?

Any odd number works. It stands in for an ancestor that does not exist and can never make a node count.

Does the parent's value ever matter on its own?

Only as the next grandparent. The current call passes it down so its grandchildren can test it.

Can the answer overflow?

No. At most 10^4 nodes with values up to 100 give a sum of at most 10^6.