From 1fef4a77be4ceefde5406a774706c00de77917cc Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 21 Nov 2022 22:31:55 +0800 Subject: [PATCH] =?UTF-8?q?Update=200112.=E8=B7=AF=E5=BE=84=E6=80=BB?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0112.路径总和.md | 49 +++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index f717f6b8..effe7649 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -1269,6 +1269,55 @@ impl Solution { } ``` +### 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(); + } + } +} + +``` +