forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1315.java
29 lines (26 loc) · 909 Bytes
/
_1315.java
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
26
27
28
29
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
public class _1315 {
public static class Solution1 {
public int sumEvenGrandparent(TreeNode root) {
if (root == null) {
return 0;
}
return dfs(root, root.left, 0) + dfs(root, root.right, 0);
}
private int dfs(TreeNode grandparent, TreeNode parent, int sum) {
if (grandparent == null || parent == null) {
return sum;
}
if (grandparent.val % 2 == 0 && parent.left != null) {
sum += parent.left.val;
}
if (grandparent.val % 2 == 0 && parent.right != null) {
sum += parent.right.val;
}
sum = dfs(parent, parent.left, sum);
sum = dfs(parent, parent.right, sum);
return sum;
}
}
}