Merge pull request #1765 from Jack-Zhang-1314/patch-21

Update 0404.左叶子之和.md about rust
This commit is contained in:
程序员Carl
2022-12-05 09:49:40 +08:00
committed by GitHub

View File

@ -576,6 +576,58 @@ object Solution {
}
```
### Rust
**递归**
```rust
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn sum_of_left_leaves(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut res = 0;
if let Some(node) = root {
if let Some(left) = &node.borrow().left {
if left.borrow().right.is_none() && left.borrow().right.is_none() {
res += left.borrow().val;
}
}
res + Self::sum_of_left_leaves(node.borrow().left.clone())
+ Self::sum_of_left_leaves(node.borrow().right.clone())
} else {
0
}
}
}
```
**迭代:**
```rust
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn sum_of_left_leaves(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut res = 0;
let mut stack = vec![root];
while !stack.is_empty() {
if let Some(node) = stack.pop().unwrap() {
if let Some(left) = &node.borrow().left {
if left.borrow().left.is_none() && left.borrow().right.is_none() {
res += left.borrow().val;
}
stack.push(Some(left.to_owned()));
}
if let Some(right) = &node.borrow().right {
stack.push(Some(right.to_owned()));
}
}
}
res
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>