Given the root of a binary tree, return the sum of values of nodes with aneven-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.

Input: root =[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]Output: 18Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
We use DFS or BFS to traverse the tree, passing down the parent and grandparent values. If the grandparent is even, add the current node’s value to the result.
structTreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
classSolution {
public:int sumEvenGrandparent(TreeNode* root, int p =1, int gp =1) {
if (!root) return0;
int res = (gp %2==0) ? root->val : 0;
res += sumEvenGrandparent(root->left, root->val, p);
res += sumEvenGrandparent(root->right, root->val, p);
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classTreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}
classSolution {
publicintsumEvenGrandparent(TreeNode root) {
return dfs(root, 1, 1);
}
privateintdfs(TreeNode node, int parent, int grandparent) {
if (node ==null) return 0;
int res = (grandparent % 2 == 0) ? node.val : 0;
res += dfs(node.left, node.val, parent);
res += dfs(node.right, node.val, parent);
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classTreeNode(var `val`: Int) {
var left: TreeNode? = nullvar right: TreeNode? = null}
classSolution {
funsumEvenGrandparent(root: TreeNode?): Int {
fundfs(node: TreeNode?, parent: Int, grandparent: Int): Int {
if (node ==null) return0var res = if (grandparent % 2==0) node.`val` else0 res += dfs(node.left, node.`val`, parent)
res += dfs(node.right, node.`val`, parent)
return res
}
return dfs(root, 1, 1)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Definition for a binary tree node.classTreeNode:
def__init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
classSolution:
defsumEvenGrandparent(self, root: TreeNode) -> int:
defdfs(node, parent, grandparent):
ifnot node:
return0 res = node.val if grandparent %2==0else0 res += dfs(node.left, node.val, parent)
res += dfs(node.right, node.val, parent)
return res
return dfs(root, 1, 1)