# [LeetCode] 1315. Sum of Nodes with Even-Valued Grandparent 祖父节点值为偶数的节点和

2022-08-31 13:00:20  阅读：71  来源： 互联网

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 题目讲解汇总(持续更新中...)

2. 关于本站的所有留言、评论、转载及引用，纯属内容发起人的个人观点，与本站观点和立场无关；
3. 关于本站的所有言论和文字，纯属内容发起人的个人观点，与本站观点和立场无关；
4. 本站文章均是网友提供，不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属；如您发现该文章侵犯了您的权益，可联系我们第一时间进行删除；
5. 本站为非盈利性的个人网站，所有内容不会用来进行牟利，也不会利用任何形式的广告来间接获益，纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。