# 1315. Sum of Nodes with Even-Valued Grandparent

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, 104]`.
• `1 <= Node.val <= 100`

``````class Solution {
public:
int sumEvenGrandparent(TreeNode* root) {
int res = 0;
dfs(root, res);
return res;
}
void dfs(TreeNode* node, int& res) {
if (!node) return;
if (node->val % 2 == 0) {
if (node->left) {
if (node->left->left) res += node->left->left->val;
if (node->left->right) res += node->left->right->val;
}
if (node->right) {
if (node->right->left) res += node->right->left->val;
if (node->right->right) res += node->right->right->val;
}
}
dfs(node->left, res);
dfs(node->right, res);
}
};
``````

``````class Solution {
public:
int sumEvenGrandparent(TreeNode* root) {
int res = 0;
dfs(root, nullptr, nullptr, res);
return res;
}
void dfs(TreeNode* node, TreeNode* parent, TreeNode* grandParent, int& res) {
if (!node) return;
if (grandParent && grandParent->val % 2 == 0) {
res += node->val;
}
dfs(node->left, node, parent, res);
dfs(node->right, node, parent, res);
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1315

https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/

https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/discuss/477095/Easy-DFS-solution

https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/discuss/477048/JavaC%2B%2BPython-1-Line-Recursive-Solution

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation