diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 2ee46c9..d977df8 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -143,4 +143,5 @@ mod p104_maximum_depth_of_binary_tree; mod p100_same_tree; mod p226_invert_binary_tree; mod p101_symmetric_tree; -mod p114_flatten_binary_tree_to_linked_list; \ No newline at end of file +mod p114_flatten_binary_tree_to_linked_list; +mod p112_path_sum; \ No newline at end of file diff --git a/src/problem/p112_path_sum.rs b/src/problem/p112_path_sum.rs new file mode 100644 index 0000000..8cc1092 --- /dev/null +++ b/src/problem/p112_path_sum.rs @@ -0,0 +1,71 @@ +/** + * [112] Path Sum + */ +pub struct Solution {} + +use crate::util::tree::{TreeNode, to_tree}; + +// 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::rc::Rc; +use std::cell::RefCell; +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() { + } +}