medium Sum of Nodes with Even-Valued Grandparent
Problem Statement
Given the root of a binary tree, return the total sum of the values of all nodes that have a grandparent with an even number. If no such nodes exist, return 0.
A grandparent of a node is defined as the parent of its parent, if both exist.
Examples
Example 1:
- Input: root =
[4, 2, 6, 3, 5, null, 8] - Expected Output:
16
- Justification: Node values
3,5, and8have4as their grandparent. Since4is even, their sum is3 + 5 + 8 = 16.
Example 2:
- Input: root =
[2, 3, 8, null, 5, 7, null, 2, 3, 4, 5] - Expected Output:
21
- Justification: Node value
5and7has2as its grandparent, and Node value4and5has grandparent8. So, sum = 5 + 7 + 4 + 5 = 21.
Example 3:
- Input: root =
[5, 9, 12, null, null, 8, 4] - Expected Output:
0
- Justification: Node values
8and4has5as its grandparent. However, since5is not even, they are not included. So, the answer is0.
Constraints:
- The number of nodes in the tree is in the range [1, 104].
- 1 <= Node.val <= 100
Try it yourself
Try solving this question here:
✅ Solution Sum of Nodes with Even-Valued Grandparent
Problem Statement
Given the root of a binary tree, return the total sum of the values of all nodes that have a grandparent with an even number. If no such nodes exist, return 0.
A grandparent of a node is defined as the parent of its parent, if both exist.
Examples
Example 1:
- Input: root =
[4, 2, 6, 3, 5, null, 8] - Expected Output:
16
- Justification: Node values
3,5, and8have4as their grandparent. Since4is even, their sum is3 + 5 + 8 = 16.
Example 2:
- Input: root =
[2, 3, 8, null, 5, 7, null, 2, 3, 4, 5] - Expected Output:
21
- Justification: Node value
5and7has2as its grandparent, and Node value4and5has grandparent8. So, sum = 5 + 7 + 4 + 5 = 21.
Example 3:
- Input: root =
[5, 9, 12, null, null, 8, 4] - Expected Output:
0
- Justification: Node values
8and4has5as its grandparent. However, since5is not even, they are not included. So, the answer is0.
Constraints:
- The number of nodes in the tree is in the range [1, 104].
- 1 <= Node.val <= 100
Solution
The algorithm for finding the sum of nodes with even-valued grandparents begins by checking if the root is null, returning 0 if true. We then initialize a queue for BFS traversal, starting with the root node, and a variable sum to keep track of the result. For each node, if its value is even, we check its left and right children for grandchildren, adding their values to the sum if they exist. All non-null children are added to the queue to continue the BFS traversal. This process repeats until all nodes are processed, and the final sum is returned.
Step-by-Step Algorithm
Step 1: Check if the tree is empty:
- If the
rootisnull, return0. This handles the case where the binary tree is empty.
Step 2: Initialize the sum variable:
- A variable
sumis initialized to0. This will keep track of the total sum of the node values that meet the condition of having an even-valued grandparent.
Step 3: Initialize a queue for level order traversal (BFS):
- A
Queueis used to perform BFS traversal starting from theroot. Therootnode is added to the queue.
Step 4: Perform BFS traversal:
-
While the queue is not empty, perform the following steps for each node:
-
Step 4.1: Remove the front node from the queue:
- Use
queue.poll()to remove the current node for processing.
- Use
-
Step 4.2: Check if the current node's value is even:
- If
current.val % 2 == 0, it means the current node has an even value. - If the current node is even-valued, we will check for its grandchildren.
- If
-
Step 4.3: Add the values of the grandchildren (if they exist):
- Left grandchild check:
- If the left child of the current node exists (
current.left != null), then check for its children (i.e., grandchildren of the current node). - If the left grandchild exists (
current.left.left != null), add its value tosum. - If the right grandchild exists (
current.left.right != null), add its value tosum.
- If the left child of the current node exists (
- Right grandchild check:
- If the right child of the current node exists (
current.right != null), then check for its children. - If the left grandchild exists (
current.right.left != null), add its value tosum. - If the right grandchild exists (
current.right.right != null), add its value tosum.
- If the right child of the current node exists (
- Left grandchild check:
-
Step 4.4: Add the children of the current node to the queue for further processing:
- If the left child exists (
current.left != null), add it to the queue. - If the right child exists (
current.right != null), add it to the queue.
- If the left child exists (
-
Step 5: Return the total sum:
- After processing all nodes in the tree, return the value of
sum, which represents the sum of all nodes with even-valued grandparents.
Algorithm Walkthrough
Step 1: Processing the Root Node (Value 4)
-
We begin at the root node with the value
4. The queue initially contains only the root node:Queue = [4]. -
The variable
sumis initialized to0. -
Since
4is an even-valued node, we now check the values of its grandchildren:- Exploring children of the left child (Node 2):
- The left child of
4is2, which has two children:3and5. Both are the grandchildren of node4. - We add the values of both
3and5tosum. - Updated
sum = 0 + 3 + 5 = 8.
- The left child of
- Exploring children of the right child (Node 6):
- The right child of
4is6. It has one child:8, which is also a grandchild of node4. - We add the value of
8tosum. - Updated
sum = 8 + 8 = 16.
- The right child of
- Exploring children of the left child (Node 2):
-
After processing the grandchildren of
4, we add its left child (2) and right child (6) to the queue for further processing.Queue = [2, 6].
Step 2: Processing Node 2
-
The next node in the queue is
2. We remove it from the queue:Queue = [6]. -
Since
2is an even-valued node, we now check the values of its grandchildren:- Exploring children of the left child (Node 3):
- The left child of
2is3. Node3has no children, so there are no grandchildren to add tosum.
- The left child of
- Exploring children of the right child (Node 5):
- The right child of
2is5. Node5also has no children, so there are no grandchildren to add tosum.
- The right child of
- Exploring children of the left child (Node 3):
-
Since there are no grandchildren for node
2, thesumremains unchanged at16. -
We then add its children (
3and5) to the queue for further processing.Queue = [6, 3, 5].
Step 3: Processing Node 6
-
The next node in the queue is
6. We remove it from the queue:Queue = [3, 5]. -
Since
6is an even-valued node, we now check the values of its grandchildren:- Exploring children of the right child (Node 8):
- The right child of
6is8. Node8has no children, so there are no grandchildren to add tosum.
- The right child of
- Exploring children of the right child (Node 8):
-
Since there are no grandchildren for node
6that haven’t already been processed, thesumremains unchanged at16. -
We then add its right child (
8) to the queue for further processing.Queue = [3, 5, 8].
Step 4: Processing Node 3
-
The next node in the queue is
3. We remove it from the queue:Queue = [5, 8]. -
Since
3is an odd-valued node, we do not process its grandchildren. -
Node
3has no children, so no further nodes are added to the queue.
Step 5: Processing Node 5
-
The next node in the queue is
5. We remove it from the queue:Queue = [8]. -
Since
5is an odd-valued node, we do not process its grandchildren. -
Node
5has no children, so no further nodes are added to the queue.
Step 6: Processing Node 8
-
The last node in the queue is
8. We remove it from the queue:Queue = []. -
Since
8is an even-valued node, we would normally check its grandchildren. However, node8has no children, so no further nodes are added to the queue.
Final Step: End of BFS Traversal
- The queue is now empty, so the BFS traversal is complete.
- The total sum of all grandchildren of even-valued nodes is
16.
Code
// class TreeNode {
// int val;
// TreeNode left;
// TreeNode right;
// // Constructor for initializing the node
// TreeNode(int val) {
// this.val = val;
// }
// }
public class Solution {
public int sumEvenGrandparent(TreeNode root) {
if (root == null) return 0;
int sum = 0; // Initialize sum to 0
Queue<TreeNode> queue = new LinkedList<>(); // Queue for level order traversal
queue.add(root); // Start with the root node
while (!queue.isEmpty()) {
TreeNode current = queue.poll(); // Get the next node from the queue
// Check if current node has an even value
if (current.val % 2 == 0) {
// If so, add the values of all grandchildren
if (current.left != null) {
if (current.left.left != null) sum += current.left.left.val; // Add left grandchild
if (current.left.right != null) sum += current.left.right.val; // Add right grandchild
}
if (current.right != null) {
if (current.right.left != null) sum += current.right.left.val; // Add left grandchild
if (current.right.right != null) sum += current.right.right.val; // Add right grandchild
}
}
// Continue with the next level nodes
if (current.left != null) queue.add(current.left);
if (current.right != null) queue.add(current.right);
}
return sum;
}
// Main method to test the function
public static void main(String[] args) {
// Construct the first tree: [4, 2, 6, 3, 5, null, 8]
TreeNode root1 = new TreeNode(4); // Root node
root1.left = new TreeNode(2); // Left child of root
root1.right = new TreeNode(6); // Right child of root
root1.left.left = new TreeNode(3); // Left child of node 2
root1.left.right = new TreeNode(5); // Right child of node 2
root1.right.right = new TreeNode(8); // Right child of node 6
// Construct the second tree: [2, 3, 8, null, 5, 7, null, 2, 3, 4, 5]
TreeNode root2 = new TreeNode(2); // Root node
root2.left = new TreeNode(3); // Left child of root
root2.right = new TreeNode(8); // Right child of root
root2.left.right = new TreeNode(5); // Right child of node 3
root2.right.left = new TreeNode(7); // Left child of node 8
root2.left.right.left = new TreeNode(2);
root2.left.right.right = new TreeNode(3);
root2.right.left.left = new TreeNode(4);
root2.right.left.right = new TreeNode(5);
// Create a Solution object to use the method
Solution solution = new Solution();
// Test the function with the first example
System.out.println("Sum for tree 1: " + solution.sumEvenGrandparent(root1)); // Expected output: 16
// Test the function with the second example
System.out.println("Sum for tree 2: " + solution.sumEvenGrandparent(root2)); // Expected output: 21
}
}
Complexity Analysis
Time Complexity
The time complexity of the algorithm is n is the number of nodes in the binary tree. This is because we traverse each node exactly once using a level order traversal, checking each node to see if it has an even-valued grandparent and adding the values of its grandchildren if applicable.
Space Complexity
The space complexity is m is the maximum number of nodes at any level of the binary tree. In the worst case, this can be proportional to the width of the tree. If the tree is a complete binary tree, this will be
🤖 Don't fully get this? Learn it with Claude
Stuck on Sum of Nodes with Even-Valued Grandparent? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Sum of Nodes with Even-Valued Grandparent** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Sum of Nodes with Even-Valued Grandparent** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Sum of Nodes with Even-Valued Grandparent**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Sum of Nodes with Even-Valued Grandparent**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.