diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index cb9d343f..7aa5f2a1 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -1219,6 +1219,111 @@ object Solution { } ``` +## rust + +### 112.路径总和.md + +递归: + +```rust +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn has_path_sum(root: Option>>, target_sum: i32) -> bool { + if root.is_none() { + return false; + } + let node = root.unwrap(); + if node.borrow().left.is_none() && node.borrow().right.is_none() { + return node.borrow().val == target_sum; + } + return Self::has_path_sum(node.borrow().left.clone(), target_sum - node.borrow().val) + || Self::has_path_sum(node.borrow().right.clone(), target_sum - node.borrow().val); + } +} +``` + +迭代: + +```rust +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn has_path_sum(root: Option>>, target_sum: i32) -> bool { + let mut stack = vec![]; + if let Some(node) = root { + stack.push((node.borrow().val, node.to_owned())); + } + while !stack.is_empty() { + let (value, node) = stack.pop().unwrap(); + if node.borrow().left.is_none() && node.borrow().right.is_none() && value == target_sum + { + return true; + } + if node.borrow().left.is_some() { + if let Some(r) = node.borrow().left.as_ref() { + stack.push((r.borrow().val + value, r.to_owned())); + } + } + if node.borrow().right.is_some() { + if let Some(r) = node.borrow().right.as_ref() { + stack.push((r.borrow().val + value, r.to_owned())); + } + } + } + false + } +``` + +### 113.路径总和-ii + +```rust +impl Solution { + pub fn path_sum(root: Option>>, target_sum: i32) -> Vec> { + let mut res = vec![]; + let mut route = vec![]; + if root.is_none() { + return res; + } else { + route.push(root.as_ref().unwrap().borrow().val); + } + Self::recur( + &root, + target_sum - root.as_ref().unwrap().borrow().val, + &mut res, + &mut route, + ); + res + } + + pub fn recur( + root: &Option>>, + sum: i32, + res: &mut Vec>, + route: &mut Vec, + ) { + let node = root.as_ref().unwrap().borrow(); + if node.left.is_none() && node.right.is_none() && sum == 0 { + res.push(route.to_vec()); + return; + } + if node.left.is_some() { + let left = node.left.as_ref().unwrap(); + route.push(left.borrow().val); + Self::recur(&node.left, sum - left.borrow().val, res, route); + route.pop(); + } + if node.right.is_some() { + let right = node.right.as_ref().unwrap(); + route.push(right.borrow().val); + Self::recur(&node.right, sum - right.borrow().val, res, route); + route.pop(); + } + } +} + +``` +