From 875680c44c216bd3e63d87133d0a108f09f8b661 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sun, 13 Nov 2022 19:35:09 +0800 Subject: [PATCH] =?UTF-8?q?Update=200104.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 70 ++++++++++++++--------- 1 file changed, 44 insertions(+), 26 deletions(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index be53c417..ee7bd50e 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -200,32 +200,6 @@ public: }; ``` -rust: -```rust -impl Solution { - pub fn max_depth(root: Option>>) -> i32 { - if root.is_none(){ - return 0; - } - let mut max_depth: i32 = 0; - let mut stack = vec![root.unwrap()]; - while !stack.is_empty() { - let num = stack.len(); - for _i in 0..num{ - let top = stack.remove(0); - if top.borrow_mut().left.is_some(){ - stack.push(top.borrow_mut().left.take().unwrap()); - } - if top.borrow_mut().right.is_some(){ - stack.push(top.borrow_mut().right.take().unwrap()); - } - } - max_depth+=1; - } - max_depth - } -``` - 那么我们可以顺便解决一下n叉树的最大深度问题 @@ -975,6 +949,50 @@ object Solution { } ``` +## rust +### 0104.二叉树的最大深度 + +递归: +```rust +impl Solution { + pub fn max_depth(root: Option>>) -> i32 { + if root.is_none() { + return 0; + } + std::cmp::max( + Self::max_depth(root.clone().unwrap().borrow().left.clone()), + Self::max_depth(root.unwrap().borrow().right.clone()), + ) + 1 + } +} +``` + +迭代: +```rust +impl Solution { + pub fn max_depth(root: Option>>) -> i32 { + if root.is_none(){ + return 0; + } + let mut max_depth: i32 = 0; + let mut stack = vec![root.unwrap()]; + while !stack.is_empty() { + let num = stack.len(); + for _i in 0..num{ + let top = stack.remove(0); + if top.borrow_mut().left.is_some(){ + stack.push(top.borrow_mut().left.take().unwrap()); + } + if top.borrow_mut().right.is_some(){ + stack.push(top.borrow_mut().right.take().unwrap()); + } + } + max_depth+=1; + } + max_depth + } +``` +