Skip to main content
Back to problems
#404
Easy Algorithms

Sum of left leaves

Tree Depth-First Search Breadth-First Search Binary Tree
62.4% acceptance
Jan 13, 2026
5777
325
Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
// 
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;

#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
  pub val: i32,
  pub left: Option<Rc<RefCell<TreeNode>>>,
  pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl Solution {
  pub fn sum_of_left_leaves(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    fn helper(node: &Option<Rc<RefCell<TreeNode>>>, is_left: bool) -> i32 {
      if let Some(n) = node {
        let n = n.borrow();
        if n.left.is_none() && n.right.is_none() && is_left {
          return n.val;
        }
        helper(&n.left, true) + helper(&n.right, false)
      } else {
        0
      }
    }
    helper(&root, false)
  }
}