From 44600f360bc25f8c7a2f6eecc662ab7f3850f3c6 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 14 Jun 2024 11:01:12 +0800 Subject: [PATCH] 20240614 Finished --- src/problem/mod.rs | 3 +- src/problem/p222_count_complete_tree_nodes.rs | 67 +++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 src/problem/p222_count_complete_tree_nodes.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index bc02c4c..396b8e9 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -147,4 +147,5 @@ mod p114_flatten_binary_tree_to_linked_list; mod p112_path_sum; mod p129_sum_root_to_leaf_numbers; mod p124_binary_tree_maximum_path_sum; -mod p173_binary_search_tree_iterator; \ No newline at end of file +mod p173_binary_search_tree_iterator; +mod p222_count_complete_tree_nodes; \ No newline at end of file diff --git a/src/problem/p222_count_complete_tree_nodes.rs b/src/problem/p222_count_complete_tree_nodes.rs new file mode 100644 index 0000000..1edd9e2 --- /dev/null +++ b/src/problem/p222_count_complete_tree_nodes.rs @@ -0,0 +1,67 @@ +/** + * [222] Count Complete Tree Nodes + */ +pub struct Solution {} + +use crate::util::tree::{TreeNode, to_tree}; + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +use std::collections::VecDeque; +impl Solution { + pub fn count_nodes(root: Option>>) -> i32 { + let mut result = 0; + let mut queue = VecDeque::new(); + + if let Some(root) = root { + queue.push_back(root); + } + + while !queue.is_empty() { + result += 1; + + let node = queue.pop_front().unwrap(); + + if let Some(left) = &node.borrow().left { + queue.push_back(Rc::clone(left)); + }; + + if let Some(right) = &node.borrow().right { + queue.push_back(Rc::clone(right)); + }; + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_222() { + } +}