From 15379361aa9b1c1c062870d9e4790ca24ae51a1b Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sun, 20 Nov 2022 16:11:25 +0800 Subject: [PATCH 1/2] =?UTF-8?q?Update=200404.=E5=B7=A6=E5=8F=B6=E5=AD=90?= =?UTF-8?q?=E4=B9=8B=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0404.左叶子之和.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 6b6fe729..3118b7c0 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -575,6 +575,31 @@ object Solution { } ``` +### Rust + +**递归** + +```rust +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn sum_of_left_leaves(root: Option>>) -> 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 + } + } +} +``` +

From 59d17ea08d37ab5e85cae19c472686fa0a4d4a69 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sun, 20 Nov 2022 16:39:42 +0800 Subject: [PATCH 2/2] =?UTF-8?q?Update=200404.=E5=B7=A6=E5=8F=B6=E5=AD=90?= =?UTF-8?q?=E4=B9=8B=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0404.左叶子之和.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 3118b7c0..f5b9ca39 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -600,6 +600,33 @@ impl Solution { } ``` +**迭代:** + +```rust +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn sum_of_left_leaves(root: Option>>) -> 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 + } +} +``` +