Sum of Nodes with Even-Valued Grandparent

Medium

Topics
TreeDFSBFS

Given the root of a binary tree, return the sum of values of every node whose grandparent has an even value. If there are no such nodes, return 0.

Example 1

92717461835
even-valued grandparent
Each shaded node sits two levels below an even value; they total 18.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18

Example 2

1
Input:  root = [1]
Output: 0

Constraints

  • 1 <= number of nodes <= 10^4
  • 1 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Each node needs to know its grandparent, which is information a plain traversal does not carry. Thread it through the recursion: pass the current node's parent and grandparent down as arguments, so every node can test its grandparent in constant time.

The alternative framing is to push rather than pull — when visiting a node with an even value, reach down two levels and add its four grandchildren. Both are O(n); the pass-down version needs no null-checking gymnastics at the leaves, which is why it reads better.

Approach

  1. Recurse with (node, parent, grandparent), starting with both ancestors null.
  2. Contribute node.val when a grandparent exists and its value is even.
  3. Recurse into both children, shifting the ancestors down by one.

Dry Run

        6
      /   \
     7     8
    / \   / \
   2   7 1   3
  /   / \     \
 9   1   4     5

grandparent 6 is even  -> grandchildren 2, 7, 1, 3   sum 13
grandparent 2 is even  -> no grandchildren
grandparent 8 is even  -> grandchild 5               sum 5
grandparent 7 is odd   -> contributes nothing

answer 18

Complexity

  • Time — O(n): one visit per node.
  • Space — O(h) for the call stack. At the stated bound of 10⁴ nodes a degenerate path needs 10,000 frames, which exceeds Python's default limit of 1,000 and Node's stack; the Python harness on this page raises the limit, and a BFS with an explicit queue carrying the ancestors is the portable alternative.

Common Pitfalls

  • Testing the parent instead of the grandparent. The off-by-one-level error passes the first example surprisingly often.
  • Returning 0 for an even-valued grandparent that has no grandchildren and treating that as a bug. It is correct; the sum is over grandchildren, so a childless subtree contributes nothing.
  • Checking g.val % 2 == 0 without first checking that g exists. The top two levels have no grandparent.
  • Collecting parent pointers in a separate map and then walking up twice. It works and is O(n), but it is two passes and a hash map where three arguments suffice.
  • Assuming values are positive and using 0 as a sentinel for "no grandparent". The constraints here do keep values at 1 or above, but the null check is the honest guard and costs nothing.
  • In the push-down variant, double-counting a grandchild reachable through two different paths. In a binary tree each node has exactly one grandparent, so this cannot happen — but say why rather than assuming.

Full Solution — all languages

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):
        def dfs(node, p, g):
            if not node: return 0
            s = node.val if (g and g.val % 2 == 0) else 0
            return s + dfs(node.left, node, p) + dfs(node.right, node, p)
        return dfs(root, None, None)
SensAI
Beta
Tap the mic to stop voice mode