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 + } +``` +