Back to course home
0% completed
Vote For New Content
Sum of Nodes with Even-Valued Grandparent (medium)
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
- Justification: Node values
3
,5
, and8
have4
as their grandparent. Since4
is even, their sum is3 + 5 + 8 = 16
.
Example 2:
- Input: root =
[2, 3, 8, null, 5, 7, null, 2, 3, 4, 5]
- Expected Output:
21
- Justification: Node value
5
and7
has2
as its grandparent, and Node value4
and5
has grandparent8
. So, sum = 5 + 7 + 4 + 5 = 21.
Example 3:
- Input: root =
[5, 9, 12, null, null, 8, 4]
- Expected Output:
0
- Justification: Node values
8
and4
has5
as its grandparent. However, since5
is not even, they are not included. So, the answer is0
.
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