Sum of Nodes with Even-Valued Grandparent

Updated on 10 July, 2025
Sum of Nodes with Even-Valued Grandparent header image

Problem Statement

In this problem, we are provided with the root of a binary tree. The task is to determine the sum of the values of nodes that have an even-valued grandparent. A node's grandparent is deemed the parent of its own parent, provided both exists in the tree structure. If no such nodes exist or if the tree does not have any even-valued grandparents, the function should return 0.

Examples

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

Constraints

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

Approach and Intuition

The task requires calculating the sum of nodes based on a specific condition related to their grandparent's value. Here is how we can approach this:

  1. Traverse the binary tree using a method suitable for accessing both children and parents such as depth-first search (DFS) or breadth-first search (BFS). A DFS approach, in particular, can be efficient in backtracking parent and grandparent relations.

  2. As you navigate through the tree, keep track of each node's parent and grandparent. This could be achieved by passing these as parameters while you recursively call the function to traverse deeper into the tree.

  3. For every node, check if it has a grandparent and if the grandparent’s value is even. To efficiently check the grandparent condition:

    • If the current node being inspected in DFS has a grandparent that is even-valued, add the current node's value to a running sum.
  4. Continue this process until all nodes have been visited. The sum at the end of the traversal will be the total value of all nodes with even-valued grandparents.

  5. Handle edge cases:

    • If the tree is empty (root is null), promptly return 0.
    • If the tree does not possess nodes with even-valued grandparents, ensure the sum remains at 0.

Through these steps, the function would explore each node, check the necessary condition of having an even-valued grandparent, and compute the cumulative sum accordingly. This systematic traversal and checking allow the solution to be both comprehensive and efficient within the given constraints.

Solutions

  • C++
cpp
class Solution {
public:
    int getNodeValue(TreeNode* node) {
        return node ? node->val : 0;
    }
        
    int sumOfEvenGrandparent(TreeNode* root) {
        if (!root) {
            return 0;
        }
            
        queue<TreeNode*> nodeQueue;
        nodeQueue.push(root);
            
        int totalSum = 0;
        while (!nodeQueue.empty()) {
            TreeNode* currentNode = nodeQueue.front();
            nodeQueue.pop();
                
            if (currentNode->val % 2 == 0) {
                if (currentNode->left) {
                    totalSum += getNodeValue(currentNode->left->left) + getNodeValue(currentNode->left->right);
                }
                if (currentNode->right) {
                    totalSum += getNodeValue(currentNode->right->left) + getNodeValue(currentNode->right->right);
                }
            }
                
            if (currentNode->left) 
                nodeQueue.push(currentNode->left);
            if (currentNode->right)
                nodeQueue.push(currentNode->right);
        }
            
        return totalSum;
    }
};

The provided C++ code defines a solution to sum the values of nodes in a binary tree that have even-valued grandparent nodes. The implementation uses a breadth-first search approach to traverse the tree and conditional logic to sum the appropriate node values.

  • getNodeValue(TreeNode* node): This helper function returns the value of the given node if it is not null; otherwise, it returns 0. This ensures safe access to node values without encountering null pointer errors.

  • sumOfEvenGrandparent(TreeNode* root): This is the primary function that computes the sum. It starts by checking if the root of the tree is null. If it is, it returns 0, indicating no nodes to process. If the root is valid, the function initializes a queue for a breadth-first search. Nodes are dequeued one by one, and if a node’s value is even, the function checks its grandchildren (if any) using the helper function getNodeValue. The value of valid grandchildren nodes is added to the total sum.

    The traversal covers all levels of the tree since after checking a node, its children (if not null) are enqueued for subsequent processing. This process repeats until all nodes are processed, and the accumulated sum of valid nodes is returned.

This method leverages a queue to manage nodes as they are processed layer by layer, ensuring that all nodes with even-valued grandparents contribute to the total sum effectively. The solution is efficient in handling trees of varying sizes and structures, providing accurate results based on the given criteria.

  • Java
java
class Solution {
    int getNodeValue(TreeNode node) {
        return node == null ? 0 : node.val;
    }
        
    public int sumEvenGrandparent(TreeNode root) {
        if (root == null) {
            return 0;
        }
            
        Queue<TreeNode> nodesQueue = new LinkedList<>();
        nodesQueue.add(root);
            
        int totalSum = 0;
        while (!nodesQueue.isEmpty()) {
            TreeNode currentNode = nodesQueue.poll();
                
            if (currentNode.val % 2 == 0) {
                if (currentNode.left != null) {
                    totalSum += getNodeValue(currentNode.left.left) + getNodeValue(currentNode.left.right);
                }
                if (currentNode.right != null) {
                    totalSum += getNodeValue(currentNode.right.left) + getNodeValue(currentNode.right.right);
                }
            }
                
            if (currentNode.left != null) 
                nodesQueue.add(currentNode.left);
            if (currentNode.right != null)
                nodesQueue.add(currentNode.right);
        }
            
        return totalSum;
    }
}

The provided Java code defines a method to calculate the sum of values of all nodes in a binary tree that have an even-valued grandparent node. It effectively utilizes a breadth-first search approach using a queue to navigate through the tree.

The key method sumEvenGrandparent(TreeNode root) initializes a queue to hold the tree nodes, integrating a level-by-level traversal. On encountering a node with an even value, the code checks for the presence of grandchildren. For any valid grandchildren nodes, their values are summed up using the helper method getNodeValue(TreeNode node), which safeguards against null nodes by returning 0.

This approach guarantees that all nodes are checked for the condition of having an even-valued grandparent, and any valid grandchildren values are accumulated into totalSum, which gets returned at the end as the solution.

Ensure proper definition and handling of the TreeNode class in your setup as it is assumed by this solution to be pre-defined with properties val, left, and right.

This approach is commendable for its simplicity and effective usage of tree traversal and condition checking techniques to solve the problem efficiently.

Comments

No comments yet.