#113
Medium Algorithms Path sum ii
Backtracking Tree Depth-First Search Binary Tree
61.8% acceptance
Feb 27, 2026
8586
170
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.
A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.
Solution
Rust
Time O(n)
Space O(n)
// 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;
impl Solution {
pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> Vec<Vec<i32>> {
let mut result = Vec::new();
let mut path = Vec::new();
fn dfs(node: Option<Rc<RefCell<TreeNode>>>, target: i32, path: &mut Vec<i32>, result: &mut Vec<Vec<i32>>) {
if let Some(n) = node {
let n_borrow = n.borrow();
path.push(n_borrow.val);
let remaining = target - n_borrow.val;
if n_borrow.left.is_none() && n_borrow.right.is_none() && remaining == 0 {
result.push(path.clone());
} else {
dfs(n_borrow.left.clone(), remaining, path, result);
dfs(n_borrow.right.clone(), remaining, path, result);
}
path.pop();
}
}
dfs(root, target_sum, &mut path, &mut result);
result
}
}