[LeetCode] Sum of Nodes with Even-Valued Grandparent

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int helper(TreeNode* node, bool grand, bool parent) {
if(!node) return 0;
int res = grand ? node->val : 0;
res += helper(node->left, parent, !(node->val & 1));
res += helper(node->right, parent, !(node->val & 1));
return res;
}
public:
int sumEvenGrandparent(TreeNode* root) {
return helper(root, false, false);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/02/PS/LeetCode/sum-of-nodes-with-even-valued-grandparent/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.