C# || How To Get The Sum Of Binary Tree Nodes With Even Valued Grandparents Using C#

The following is a module with functions which demonstrates how to get the sum of binary tree nodes with even valued grandparents using C#.


1. Sum Even Grandparent – Problem Statement

Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0.

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

Example 1:

Example 1


Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18
Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.

Example 2:

Example 2


Input: root = [1]
Output: 0


2. Sum Even Grandparent – Solution

The following is a solution which demonstrates how to get the sum of binary tree nodes with even valued grandparents.

The idea of this solution is to simply traverse the tree, and for each recursive call, we keep track of the parent node and the grandparent node of each node.

If a node has a grandparent, we check to see if it is an even number. If it is, the result is incremented.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


18
0

Was this article helpful?
👍 YesNo

Leave a Reply