From 933cada6dbcd4169e3345828e886a127688db619 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 15 Nov 2022 21:19:56 +0800 Subject: [PATCH] =?UTF-8?q?Update=200222.=E5=AE=8C=E5=85=A8=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E8=8A=82=E7=82=B9=E4=B8=AA=E6=95=B0?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0222.完全二叉树的节点个数.md | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index bfb9ac0f..8a3a15f3 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -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>>) -> 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 + } +} +``` +