-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsum-of-nodes-with-even-valued-grandparent.java
More file actions
53 lines (50 loc) · 1.3 KB
/
sum-of-nodes-with-even-valued-grandparent.java
File metadata and controls
53 lines (50 loc) · 1.3 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
import java.util.*;
class Solution {
public int sumEvenGrandparent(TreeNode root) {
//start with 2
if (root == null) {
return 0;
}
ArrayList<TreeNode> tree = new ArrayList<>();
tree.add(root);
int sum = 0;
for (int i = 0; i < tree.size(); i++) {
TreeNode t = tree.get(i);
if (t.left != null) {
tree.add(t.left);
}
if (t.right != null) {
tree.add(t.right);
}
if (t.val % 2 == 0) {
sum += sumOfGrandchildren(t, 2);
}
}
return sum;
}
public int sumOfGrandchildren(TreeNode root, int g) {
if (root == null) {
return 0;
}
if (g == 0) {
return root.val;
} else {
return sumOfGrandchildren(root.left, g - 1) + sumOfGrandchildren(root.right, g - 1);
}
}
}