树深度 rust实现

This commit is contained in:
3Xpl0it3r
2022-05-18 18:31:37 +08:00
parent 1c369bb836
commit b8b62ffc32
2 changed files with 91 additions and 0 deletions

View File

@ -192,6 +192,33 @@ 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叉树的最大深度问题
# 559.n叉树的最大深度

View File

@ -488,5 +488,69 @@ func minDepth(_ root: TreeNode?) -> Int {
}
```
rust:
```rust
impl Solution {
pub fn min_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
return Solution::bfs(root)
}
// 递归
pub fn dfs(node: Option<Rc<RefCell<TreeNode>>>) -> i32{
if node.is_none(){
return 0;
}
let parent = node.unwrap();
let left_child = parent.borrow_mut().left.take();
let right_child = parent.borrow_mut().right.take();
if left_child.is_none() && right_child.is_none(){
return 1;
}
let mut min_depth = i32::MAX;
if left_child.is_some(){
let left_depth = Solution::dfs(left_child);
if left_depth <= min_depth{
min_depth = left_depth
}
}
if right_child.is_some(){
let right_depth = Solution::dfs(right_child);
if right_depth <= min_depth{
min_depth = right_depth
}
}
min_depth + 1
}
// 迭代
pub fn bfs(node: Option<Rc<RefCell<TreeNode>>>) -> i32{
let mut min_depth = 0;
if node.is_none(){
return min_depth
}
let mut stack = vec![node.unwrap()];
while !stack.is_empty(){
min_depth += 1;
let num = stack.len();
for _i in 0..num{
let top = stack.remove(0);
let left_child = top.borrow_mut().left.take();
let right_child = top.borrow_mut().right.take();
if left_child.is_none() && right_child.is_none(){
return min_depth;
}
if left_child.is_some(){
stack.push(left_child.unwrap());
}
if right_child.is_some(){
stack.push(right_child.unwrap());
}
}
}
min_depth
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>