From 47b7cf3cae785ec43be3e08dc8db8143d3f9aaca Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sun, 20 Nov 2022 22:06:39 +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 | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 482787bf..f717f6b8 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -1217,6 +1217,8 @@ object Solution { ### 112.路径总和.md +递归: + ```rust use std::rc::Rc; use std::cell::RefCell; @@ -1235,6 +1237,38 @@ impl Solution { } ``` +迭代: + +```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 + } +``` +