mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Update 0222.完全二叉树的节点个数.md
This commit is contained in:
@ -814,6 +814,35 @@ impl Solution {
|
||||
}
|
||||
```
|
||||
|
||||
// 迭代
|
||||
```rust
|
||||
use std::rc::Rc;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::VecDeque;
|
||||
impl Solution {
|
||||
pub fn count_nodes(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() {
|
||||
for _ in 0..queue.len() {
|
||||
let node = queue.pop_front().unwrap().unwrap();
|
||||
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 += 1;
|
||||
}
|
||||
}
|
||||
res
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<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