Sum of Nodes with Even-Valued Grandparent Java Solution
Problem:
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
Solution:
public int sumEvenGrandparent(TreeNode root) {
ArrayList<TreeNode> list = new ArrayList<>();
fillList(root, list);
int res = 0;
for(TreeNode node: list) {
res+= getSumOfGrandChild(node, 2);
}
return res;
}
public void fillList(TreeNode root, ArrayList<TreeNode> list) {
if(root == null) return;
if(root.val%2==0)
list.add(root);
fillList(root.left, list);
fillList(root.right, list);
}
public int getSumOfGrandChild(TreeNode root, int depth) {
if(root == null ) return 0;
if(depth == 0) return root.val;
if(depth < 0) return 0;
return getSumOfGrandChild(root.left, depth-1) + getSumOfGrandChild(root.right, depth-1);
}
0 Comments:
Post a Comment