Skip to main content
Back to problems
#1315
Medium Algorithms

Sum of nodes with even valued grandparent

Tree Depth-First Search Breadth-First Search Binary Tree
85.9% acceptance
Feb 27, 2026
2827
79
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  pub fn sum_even_grandparent(root: Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>) -> i32 {
    Self::dfs(&root, -1, -1)
  }

  fn dfs(node: &Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>, parent: i32, grandparent: i32) -> i32 {
    if let Some(n) = node {
      let val = n.borrow().val;
      let mut sum = if grandparent % 2 == 0 && grandparent > 0 { val } else { 0 };
      sum += Self::dfs(&n.borrow().left.clone(), val, parent);
      sum += Self::dfs(&n.borrow().right.clone(), val, parent);
      sum
    } else {
      0
    }
  }
}