less than 1 minute read

Given a binary tree root, return the sum of all node values whose grandparents have an even value.

Constraints

  • 0 ≤ n ≤ 100,000 where n is the number of nodes in root

https://binarysearch.com/problems/Sum-of-Nodes-with-Even-Grandparent-Values

ExamplesPermalink

Example 1Permalink

Input

  • root =
example1Root 0 8 1 4 0->1 2 3 0->2 3 6 1->3 4 7 1->4 5 2 4->5

Output

  • answer = 15

Explanation

Nodes 6, 7, and 2 have an even value grandparent.

SolutionPermalink

/**
* class Tree {
* public:
* int val;
* Tree *left;
* Tree *right;
* };
*/
int solveR(Tree *node, int *res)
{
if (!node)
{
return 0;
}
int left = solveR(node->left, res);
int right = solveR(node->right, res);
if (node->val % 2 == 0)
{
*res += left + right;
}
return (node->left ? node->left->val : 0) + (node->right ? node->right->val : 0);
}
int solve(Tree *root)
{
int res = 0;
solveR(root, &res);
return res;
}

Leave a comment