Sum of Nodes with Even-Valued Grandparent
Medium
Topics
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
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
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
- Recurse with
(node, parent, grandparent), starting with both ancestors null. - Contribute
node.valwhen a grandparent exists and its value is even. - 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 18Complexity
- 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 == 0without first checking thatgexists. 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)import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int sumEvenGrandparent(TreeNode root) {
return dfs(root, null, null);
}
private int dfs(TreeNode node, TreeNode p, TreeNode g) {
if (node == null) return 0;
int s = (g != null && g.val % 2 == 0) ? node.val : 0;
return s + dfs(node.left, node, p) + dfs(node.right, node, p);
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int sumEvenGrandparent(TreeNode* root) {
function<int(TreeNode*,TreeNode*,TreeNode*)> dfs = [&](TreeNode* node, TreeNode* p, TreeNode* g) -> int {
if (!node) return 0;
int s = (g && g->val % 2 == 0) ? node->val : 0;
return s + dfs(node->left, node, p) + dfs(node->right, node, p);
};
return dfs(root, nullptr, nullptr);
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var sumEvenGrandparent = function(root) {
const dfs = (node, p, g) => {
if (!node) return 0;
const s = (g && g.val % 2 === 0) ? node.val : 0;
return s + dfs(node.left, node, p) + dfs(node.right, node, p);
};
return dfs(root, null, null);
};