mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #1754 from Jack-Zhang-1314/patch-15
Update 0104.二叉树的最大深度.md about rust
This commit is contained in:
@ -200,32 +200,6 @@ public:
|
||||
};
|
||||
```
|
||||
|
||||
rust:
|
||||
```rust
|
||||
impl Solution {
|
||||
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> 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<Rc<RefCell<TreeNode>>>) -> 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<Rc<RefCell<TreeNode>>>) -> 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
|
||||
}
|
||||
```
|
||||
|
||||
<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