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:
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:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
// ============================================================================ // Author: Kenneth Perkins // Date: Oct 20, 2021 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Determines how to get the sum of even valued tree grandparents // ============================================================================ /** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { private int result = 0; public int SumEvenGrandparent(TreeNode root) { Traverse(root, null, null); return result; } private void Traverse(TreeNode node, TreeNode parent, TreeNode grandParent) { if (node == null) { return; } // If a grandparent exists and its an even number, // add the current node value to the result if (grandParent != null && grandParent.val % 2 == 0) { result += node.val; } // Keep exploring left & right nodes // setting the current node as the parent // and the current parent node as the grandparent Traverse(node.left, node, parent); Traverse(node.right, node, parent); } }// http://programmingnotes.org/ |
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
Leave a Reply