#112
Easy Algorithms Path sum
Tree Depth-First Search Breadth-First Search Binary Tree
54.5% acceptance
Feb 27, 2026
10661
1213
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
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 has_path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> bool {
let Some(root_node) = root else { return false; };
let mut stack = vec![(root_node, target_sum)];
while let Some((node, remaining)) = stack.pop() {
let node_borrow = node.borrow();
let new_remaining = remaining - node_borrow.val;
if node_borrow.left.is_none() && node_borrow.right.is_none() {
if new_remaining == 0 {
return true;
}
continue;
}
if let Some(left) = &node_borrow.left {
stack.push((Rc::clone(left), new_remaining));
}
if let Some(right) = &node_borrow.right {
stack.push((Rc::clone(right), new_remaining));
}
}
false
}
}