package leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/
 */
public class Problem1315 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public int sumEvenGrandparent(TreeNode root) {
        return sumEvenGrandparent(root, new ArrayList<>());
    }

    private static int sumEvenGrandparent(TreeNode root, List<Integer> grandparents) {
        if (root == null) {
            return 0;
        }
        int even = 0;
        if (grandparents.size() >= 2 && grandparents.get(grandparents.size() - 2) % 2 == 0) {
            even = root.val;
        }
        List<Integer> copy = new ArrayList<>(grandparents);
        copy.add(root.val);
        int left = sumEvenGrandparent(root.left, copy);
        copy = new ArrayList<>(grandparents);
        copy.add(root.val);
        int right = sumEvenGrandparent(root.right, copy);
        return even + left + right;
    }
}

@@ -16,60 +16,8 @@
 e;%0A%0A
-import java.util.ArrayList;%0Aimport java.util.List;%0A%0A
 /**%0A
@@ -382,25 +382,14 @@
 ot, 
-new ArrayList%3C%3E()
+-1, -1
 );%0A 
@@ -455,34 +455,35 @@
 ot, 
-List%3CInteger%3E grandparents
+int grandparent, int parent
 ) %7B%0A
@@ -591,66 +591,8 @@
 rent
-s.size() %3E= 2 && grandparents.get(grandparents.size() - 2)
  %25 2
@@ -651,207 +651,57 @@
     
-List%3CInteger%3E copy = new ArrayList%3C%3E(grandparents);%0A        copy.add(root.val);%0A        int left = sumEvenGrandparent(root.left, copy);%0A        copy = new ArrayList%3C%3E(grandparents);%0A        copy.add(
+int left = sumEvenGrandparent(root.left, parent, 
 root
@@ -762,12 +762,24 @@
 ht, 
-copy
+parent, root.val
 );%0A 

Solve problem 1315