Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.
Move from brute-force thinking to an efficient approach using tree strategy.
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
Constraints:
[1, 104].1 <= Node.val <= 100Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Tree
[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
[1]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1315: Sum of Nodes with Even-Valued Grandparent
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumEvenGrandparent(TreeNode root) {
return dfs(root, 1);
}
private int dfs(TreeNode root, int x) {
if (root == null) {
return 0;
}
int ans = dfs(root.left, root.val) + dfs(root.right, root.val);
if (x % 2 == 0) {
if (root.left != null) {
ans += root.left.val;
}
if (root.right != null) {
ans += root.right.val;
}
}
return ans;
}
}
// Accepted solution for LeetCode #1315: Sum of Nodes with Even-Valued Grandparent
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumEvenGrandparent(root *TreeNode) int {
var dfs func(*TreeNode, int) int
dfs = func(root *TreeNode, x int) int {
if root == nil {
return 0
}
ans := dfs(root.Left, root.Val) + dfs(root.Right, root.Val)
if x%2 == 0 {
if root.Left != nil {
ans += root.Left.Val
}
if root.Right != nil {
ans += root.Right.Val
}
}
return ans
}
return dfs(root, 1)
}
# Accepted solution for LeetCode #1315: Sum of Nodes with Even-Valued Grandparent
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
def dfs(root: TreeNode, x: int) -> int:
if root is None:
return 0
ans = dfs(root.left, root.val) + dfs(root.right, root.val)
if x % 2 == 0:
if root.left:
ans += root.left.val
if root.right:
ans += root.right.val
return ans
return dfs(root, 1)
// Accepted solution for LeetCode #1315: Sum of Nodes with Even-Valued Grandparent
struct Solution;
use rustgym_util::*;
trait Preorder {
fn preorder(&self, parent: bool, grand_parent: bool, sum: &mut i32);
}
impl Preorder for TreeLink {
fn preorder(&self, parent: bool, grand_parent: bool, sum: &mut i32) {
if let Some(node) = self {
let val = node.borrow().val;
let left = &node.borrow().left;
let right = &node.borrow().right;
if grand_parent {
*sum += val;
}
left.preorder(val % 2 == 0, parent, sum);
right.preorder(val % 2 == 0, parent, sum);
}
}
}
impl Solution {
fn sum_even_grandparent(root: TreeLink) -> i32 {
let mut res = 0;
root.preorder(false, false, &mut res);
res
}
}
#[test]
fn test() {
let root = tree!(
6,
tree!(7, tree!(2, tree!(9), None), tree!(7, tree!(1), tree!(4))),
tree!(8, tree!(1), tree!(3, None, tree!(5)))
);
let res = 18;
assert_eq!(Solution::sum_even_grandparent(root), res);
}
// Accepted solution for LeetCode #1315: Sum of Nodes with Even-Valued Grandparent
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function sumEvenGrandparent(root: TreeNode | null): number {
const dfs = (root: TreeNode | null, x: number): number => {
if (!root) {
return 0;
}
const { val, left, right } = root;
let ans = dfs(left, val) + dfs(right, val);
if (x % 2 === 0) {
ans += left?.val ?? 0;
ans += right?.val ?? 0;
}
return ans;
};
return dfs(root, 1);
}
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.