mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0112.路径总和.md
This commit is contained in:
@ -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"/>
|
||||
|
Reference in New Issue
Block a user