/** * [112] Path Sum */ pub struct Solution {} use crate::util::tree::{to_tree, TreeNode}; // submission codes start here // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option>>, // pub right: Option>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { fn dfs(node: &Rc>, current_sum: i32, target_sum: i32) -> bool { // 到达叶子节点 if node.borrow().left.is_none() && node.borrow().right.is_none() { return current_sum + node.borrow().val == target_sum; } if let Some(left) = &node.borrow().left { if Self::dfs(left, current_sum + node.borrow().val, target_sum) { return true; } } if let Some(right) = &node.borrow().right { if Self::dfs(right, current_sum + node.borrow().val, target_sum) { return true; } } false } pub fn has_path_sum(root: Option>>, target_sum: i32) -> bool { if let Some(root) = root { return Self::dfs(&root, 0, target_sum); } false } } // submission codes end #[cfg(test)] mod tests { use super::*; #[test] fn test_112() {} }