Update 0112.路径总和.md

This commit is contained in:
fw_qaq
2022-11-21 22:31:55 +08:00
committed by GitHub
parent 47b7cf3cae
commit 1fef4a77be

View File

@ -1269,6 +1269,55 @@ impl Solution {
}
```
### 113.路径总和-ii
```rust
impl Solution {
pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> Vec<Vec<i32>> {
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<Rc<RefCell<TreeNode>>>,
sum: i32,
res: &mut Vec<Vec<i32>>,
route: &mut Vec<i32>,
) {
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();
}
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>