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 of Nodes with Even-Valued Grandparent INPUT 6 7 8 2 7 1 3 9 1 4 5 Legend: Even-valued (Grandparent) Children of GP Grandchildren (counted) [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] ALGORITHM STEPS 1 DFS Traversal Pass parent and grandparent info to each recursive call 2 Check Grandparent If grandparent exists and is even, add node value 3 Recurse Children Current node becomes parent, parent becomes grandparent 4 Sum Results Accumulate all valid grandchildren values Grandchildren of Even Nodes: GP=6: 2,7,1,3 (children of 7,8) GP=8: 5 (child of 3) From GP 6: 9+1+4 = 14 From GP 8: 5 (but need level 3) FINAL RESULT Nodes with Even GP: 6 7 8 2 7 1 3 9 1 4 5 Calculation: 9 + 1 + 4 + 5 = 18 Output: 18 Key Insight: DFS with grandparent tracking allows O(n) traversal. Pass both parent and grandparent values to each recursive call. When grandparent is even (value % 2 == 0), add current node's value to the sum. TutorialsPoint - Sum of Nodes with Even-Valued Grandparent | DFS with Grandparent Tracking
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