Merge branch 'youngyangyang04:master' into leetcode-modify-the-code-of-the-BinaryTree

This commit is contained in:
Yuhao Ju
2022-12-01 21:51:40 +08:00
committed by GitHub
4 changed files with 119 additions and 9 deletions

View File

@@ -793,6 +793,52 @@ object Solution {
}
```
rust:
// 递归
```rust
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn count_nodes(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
if root.is_none() {
return 0;
}
1 + Self::count_nodes(Rc::clone(root.as_ref().unwrap()).borrow().left.clone())
+ Self::count_nodes(root.unwrap().borrow().right.clone())
}
}
```
// 迭代
```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"/>