This commit is contained in:
Håkon Størdal 2025-05-02 19:22:31 +02:00
parent d06e49bcd7
commit 7b8a1436c5
6 changed files with 256 additions and 0 deletions

6
path-sum-112/Cargo.toml Normal file
View file

@ -0,0 +1,6 @@
[package]
name = "path-sum-112"
version = "0.1.0"
edition = "2024"
[dependencies]

50
path-sum-112/src/main.rs Normal file
View file

@ -0,0 +1,50 @@
// 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,
}
}
}
struct Solution;
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn has_path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> bool {
// Base case: If the tree is empty, there's no path
if root.is_none() {
return false;
}
let node = root.unwrap();
let node_ref = node.borrow();
let current_val = node_ref.val;
// If this is a leaf node, check if the value equals the remaining target sum
if node_ref.left.is_none() && node_ref.right.is_none() {
return current_val == target_sum;
}
// Otherwise, check if either subtree has a path with the remaining sum
let remaining_sum = target_sum - current_val;
Solution::has_path_sum(node_ref.left.clone(), remaining_sum)
|| Solution::has_path_sum(node_ref.right.clone(), remaining_sum)
}
}
fn main() {
println!("Hello, world!");
}