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);  // The parent and the grandparent are odd at first.
  }

 private:
  int dfs(TreeNode* root, int p, int gp) {
    if (root == nullptr)
      return 0;
    return (gp % 2 == 0 ? root->val : 0) +  //
           dfs(root->left, root->val, p) +  //
           dfs(root->right, root->val, p);
  }
};
 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); // The parent and the grandparent are odd at first.
  }

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