Skip to content

1315. Sum of Nodes with Even-Valued Grandparent 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int sumEvenGrandparent(TreeNode* root) {
    return dfs(root, 1, 1);  // parent and grandparent are odd at first
  }

 private:
  int dfs(TreeNode* root, int p, int gp) {
    if (!root)
      return 0;
    return dfs(root->left, root->val, p) +
           dfs(root->right, root->val, p) +
           (gp % 2 == 0 ? root->val : 0);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int sumEvenGrandparent(TreeNode root) {
    return dfs(root, 1, 1); // parent and grandparent are odd at first
  }

  private int dfs(TreeNode root, int p, int gp) {
    if (root == null)
      return 0;
    return dfs(root.left, root.val, p) +
           dfs(root.right, root.val, p) +
           (gp % 2 == 0 ? root.val : 0);
  }
}