Add Values Whose Grandparent Is Even

Quick Overview

Add Values Whose Grandparent Is Even. For each native binary-tree node, inspect its grandparent, meaning its parent's parent when it exists.

Add Values Whose Grandparent Is Even

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem For each native binary-tree node, inspect its grandparent, meaning its parent's parent when it exists. Return the sum of values of exactly those nodes whose grandparent value is even. Return 0 if there are none. ```cpp class Solution { public: int sumEvenGrandparent(TreeNode* root); }; ``` ### Examples **Example 1:** ```text Input: root = [2,3,4,5,6] Output: 11 Explanation: Nodes5 and6 have even-valued grandparent2, so their values sum to11. ``` **Example 2:** ```text Input: root = [1,2,3,4] Output: 0 Explanation: The only node with a grandparent is4, whose grandparent1 is odd. ``` ### Constraints - The tree has 1 to 10000 nodes. - Each node value is an integer from 1 through 100. ### Contract considerations Retain the native TreeNode pointer and do not reinterpret an array-index grandparent formula for an arbitrary tree. ```hint Read the boundary condition Distinguish a qualifying grandparent from a qualifying parent. Include nodes that have no grandparent. ``` ### Boundary reminders Retain the native TreeNode pointer and do not reinterpret an array-index grandparent formula for an arbitrary tree.

Overview: Add Values Whose Grandparent Is Even. For each native binary-tree node, inspect its grandparent, meaning its parent's parent when it exists.

Amazon logo
Amazon
Jun 12, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

For each native binary-tree node, inspect its grandparent, meaning its parent's parent when it exists. Return the sum of values of exactly those nodes whose grandparent value is even. Return 0 if there are none.

class Solution {
public:
    int sumEvenGrandparent(TreeNode* root);
};

Examples

Example 1:

Input: root = [2,3,4,5,6]
Output: 11
Explanation: Nodes5 and6 have even-valued grandparent2, so their values sum to11.

Example 2:

Input: root = [1,2,3,4]
Output: 0
Explanation: The only node with a grandparent is4, whose grandparent1 is odd.

Constraints

  • The tree has 1 to 10000 nodes.
  • Each node value is an integer from 1 through 100.

Contract considerations

Retain the native TreeNode pointer and do not reinterpret an array-index grandparent formula for an arbitrary tree.

Boundary reminders

Retain the native TreeNode pointer and do not reinterpret an array-index grandparent formula for an arbitrary tree.