Update 0111.二叉树的最小深度.md

This commit is contained in:
fw_qaq
2022-11-13 23:17:30 +08:00
committed by GitHub
parent b56bc32a23
commit 8b26d8e193

View File

@ -574,37 +574,21 @@ object Solution {
rust: rust:
```rust ```rust
impl Solution { 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{ pub fn min_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
if node.is_none(){ if let Some(node) = root {
return 0; match (node.borrow().left.clone(), node.borrow().right.clone()) {
(Some(n1), None) => 1 + Self::min_depth(Some(n1)),
(None, Some(n2)) => 1 + Self::min_depth(Some(n2)),
(Some(n1), Some(n2)) => {
1 + std::cmp::min(Self::min_depth(Some(n1)), Self::min_depth(Some(n2)))
} }
let parent = node.unwrap(); _ => 1,
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; } else {
if left_child.is_some(){ 0
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{ pub fn bfs(node: Option<Rc<RefCell<TreeNode>>>) -> i32{