Sum of Nodes with Even-Valued Grandparent

medium binary tree dfs recursion

Problem

Given the root of a binary tree, return the sum of the values of every node whose grandparent (its parent's parent) has an even value. If there is no such node, return 0.

Inputroot = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output18
Grandparent 6 contributes its grandchildren 2, 7, 1, 3; grandparent 8 contributes 5. Sum = 2+7+1+3+5 = 18.

def sumEvenGrandparent(root):
    def dfs(node, parent, grand):
        if not node:
            return 0
        total = 0
        if grand is not None and grand % 2 == 0:
            total += node.val
        total += dfs(node.left, node.val, parent)
        total += dfs(node.right, node.val, parent)
        return total
    return dfs(root, None, None)
function sumEvenGrandparent(root) {
  function dfs(node, parent, grand) {
    if (!node) return 0;
    let total = 0;
    if (grand !== null && grand % 2 === 0) {
      total += node.val;
    }
    total += dfs(node.left, node.val, parent);
    total += dfs(node.right, node.val, parent);
    return total;
  }
  return dfs(root, null, null);
}
int sumEvenGrandparent(TreeNode root) {
    return dfs(root, -1, -1);
}

int dfs(TreeNode node, int parent, int grand) {
    if (node == null) return 0;
    int total = 0;
    if (grand != -1 && grand % 2 == 0) {
        total += node.val;
    }
    total += dfs(node.left, node.val, parent);
    total += dfs(node.right, node.val, parent);
    return total;
}
int dfs(TreeNode* node, int parent, int grand) {
    if (!node) return 0;
    int total = 0;
    if (grand != -1 && grand % 2 == 0) {
        total += node->val;
    }
    total += dfs(node->left, node->val, parent);
    total += dfs(node->right, node->val, parent);
    return total;
}

int sumEvenGrandparent(TreeNode* root) {
    return dfs(root, -1, -1);
}
Time: O(n) Space: O(h)