Grokking Tree Coding Patterns for Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Sum of Nodes with Even-Valued Grandparent (medium)
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

Given the root of a binary tree, return the total sum of the values of all nodes that have a grandparent with an even number. If no such nodes exist, return 0.

A grandparent of a node is defined as the parent of its parent, if both exist.

Examples

Example 1:

  • Input: root = [4, 2, 6, 3, 5, null, 8]
  • Expected Output: 16
Image
  • Justification: Node values 3, 5, and 8 have 4 as their grandparent. Since 4 is even, their sum is 3 + 5 + 8 = 16.

Example 2:

  • Input: root = [2, 3, 8, null, 5, 7, null, 2, 3, 4, 5]
  • Expected Output: 21
Image
  • Justification: Node value 5 and 7 has 2 as its grandparent, and Node value 4 and 5 has grandparent 8. So, sum = 5 + 7 + 4 + 5 = 21.

Example 3:

  • Input: root = [5, 9, 12, null, null, 8, 4]
  • Expected Output: 0
Image
  • Justification: Node values 8 and 4 has 5 as its grandparent. However, since 5 is not even, they are not included. So, the answer is 0.

Constraints:

  • The number of nodes in the tree is in the range [1, 10<sup>4</sup>].
  • 1 <= Node.val <= 100

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible