Update 0112.路径总和.md

This commit is contained in:
fw_qaq
2022-11-20 22:06:39 +08:00
committed by GitHub
parent d3e35b3ae9
commit 47b7cf3cae

View File

@ -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<Rc<RefCell<TreeNode>>>, 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
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>