Sum of Nodes with Even-Valued Grandparent - Problem

Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent.

A grandparent of a node is the parent of its parent if it exists.

If there are no nodes with an even-valued grandparent, return 0.

Input & Output

Example 1 — Basic Tree
$ Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18
💡 Note: Nodes with even-valued grandparent 6: nodes 7,1,4 (sum=12). Nodes with even-valued grandparent 8: node 5 (sum=5). But wait, let me recalculate: grandchildren of 6 are 2,7,1,3 and grandchildren of 8 are null,5. So sum = 2+7+1+3+5 = 18.
Example 2 — Simple Tree
$ Input: root = [6,7,8,2,4,1,3]
Output: 10
💡 Note: Node 6 is even. Its grandchildren are 2,4,1,3. Sum = 2+4+1+3 = 10
Example 3 — No Even Grandparents
$ Input: root = [1]
Output: 0
💡 Note: Only one node exists, no grandchildren possible

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • 1 ≤ Node.val ≤ 100

Visualization

Tap to expand
Sum Nodes with Even-Valued Grandparent6Even Grandparent782413Grandchildren of Even GPGrandparent 6 is even → Sum grandchildren: 2+4+1+3Result: 10
Understanding the Visualization
1
Input Tree
Binary tree with node values
2
Find Grandchildren
Identify nodes with even-valued grandparents
3
Sum Values
Add up all qualifying node values
Key Takeaway
🎯 Key Insight: Track grandparent info during DFS traversal for optimal O(n) solution
Asked in
Facebook 15 Amazon 12
18.5K Views
Medium Frequency
~15 min Avg. Time
891 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen