Skip to main content
Back to problems
#437
Medium Algorithms

Path sum iii

Tree Depth-First Search Binary Tree
46.3% acceptance
Jan 13, 2026
11869
572
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

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;
use std::collections::HashMap;

impl Solution {
  pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> i32 {
    let mut prefix_sum = HashMap::new();
    prefix_sum.insert(0i64, 1);
    Self::dfs(&root, 0, target_sum as i64, &mut prefix_sum)
  }
  
  fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, curr_sum: i64, target: i64, prefix_sum: &mut HashMap<i64, i32>) -> i32 {
    if let Some(n) = node {
      let n = n.borrow();
      let curr_sum = curr_sum + n.val as i64;
      let mut count = *prefix_sum.get(&(curr_sum - target)).unwrap_or(&0);
      
      *prefix_sum.entry(curr_sum).or_insert(0) += 1;
      
      count += Self::dfs(&n.left, curr_sum, target, prefix_sum);
      count += Self::dfs(&n.right, curr_sum, target, prefix_sum);
      
      *prefix_sum.get_mut(&curr_sum).unwrap() -= 1;
      
      count
    } else {
      0
    }
  }
}