mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
Update 0111.二叉树的最小深度.md
This commit is contained in:
@ -591,33 +591,30 @@ impl Solution {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 迭代
|
// 迭代
|
||||||
pub fn bfs(node: Option<Rc<RefCell<TreeNode>>>) -> i32{
|
pub fn min_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
|
||||||
let mut min_depth = 0;
|
let mut res = 0;
|
||||||
if node.is_none(){
|
let mut queue = VecDeque::new();
|
||||||
return min_depth
|
if root.is_some() {
|
||||||
|
queue.push_back(root);
|
||||||
}
|
}
|
||||||
let mut stack = vec![node.unwrap()];
|
while !queue.is_empty() {
|
||||||
while !stack.is_empty(){
|
res += 1;
|
||||||
min_depth += 1;
|
for _ in 0..queue.len() {
|
||||||
let num = stack.len();
|
let node = queue.pop_front().unwrap().unwrap();
|
||||||
for _i in 0..num{
|
if node.borrow().left.is_none() && node.borrow().right.is_none() {
|
||||||
let top = stack.remove(0);
|
return res;
|
||||||
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(){
|
if node.borrow().left.is_some() {
|
||||||
stack.push(left_child.unwrap());
|
queue.push_back(node.borrow().left.clone());
|
||||||
}
|
}
|
||||||
if right_child.is_some(){
|
if node.borrow().right.is_some() {
|
||||||
stack.push(right_child.unwrap());
|
queue.push_back(node.borrow().right.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
min_depth
|
res
|
||||||
}
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
|
Reference in New Issue
Block a user