mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Update 0102.二叉树的层序遍历.md
This commit is contained in:
@ -2850,6 +2850,39 @@ object Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
rust:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
use std::rc::Rc;
|
||||||
|
impl Solution {
|
||||||
|
pub fn min_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
|
||||||
|
let mut res = 0;
|
||||||
|
let mut queue = VecDeque::new();
|
||||||
|
if root.is_some() {
|
||||||
|
queue.push_back(root);
|
||||||
|
}
|
||||||
|
while !queue.is_empty() {
|
||||||
|
res += 1;
|
||||||
|
for _ in 0..queue.len() {
|
||||||
|
let node = queue.pop_front().unwrap().unwrap();
|
||||||
|
if node.borrow().left.is_none() && node.borrow().right.is_none() {
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
if node.borrow().left.is_some() {
|
||||||
|
queue.push_back(node.borrow().left.clone());
|
||||||
|
}
|
||||||
|
if node.borrow().right.is_some() {
|
||||||
|
queue.push_back(node.borrow().right.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
# 总结
|
# 总结
|
||||||
|
|
||||||
二叉树的层序遍历,**就是图论中的广度优先搜索在二叉树中的应用**,需要借助队列来实现(此时又发现队列的一个应用了)。
|
二叉树的层序遍历,**就是图论中的广度优先搜索在二叉树中的应用**,需要借助队列来实现(此时又发现队列的一个应用了)。
|
||||||
|
Reference in New Issue
Block a user