From d6d6d5cea5824f921620fc3368001eb8fbf72e3d Mon Sep 17 00:00:00 2001 From: jackfiled Date: Tue, 12 Mar 2024 15:14:49 +0800 Subject: [PATCH] 20240312 Finished --- src/problem/mod.rs | 3 +- ..._elements_in_a_contaminated_binary_tree.rs | 89 +++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 src/problem/p1261_find_elements_in_a_contaminated_binary_tree.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 344a10e..60dd272 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -70,4 +70,5 @@ mod p2575_find_the_divisibility_array_of_a_string; mod p2834_find_the_minimum_possible_sum_of_a_beautiful_array; mod p2386_find_the_k_sum_of_an_array; mod p299_bulls_and_cows; -mod p2129_capitalize_the_title; \ No newline at end of file +mod p2129_capitalize_the_title; +mod p1261_find_elements_in_a_contaminated_binary_tree; \ No newline at end of file diff --git a/src/problem/p1261_find_elements_in_a_contaminated_binary_tree.rs b/src/problem/p1261_find_elements_in_a_contaminated_binary_tree.rs new file mode 100644 index 0000000..8ae235a --- /dev/null +++ b/src/problem/p1261_find_elements_in_a_contaminated_binary_tree.rs @@ -0,0 +1,89 @@ +/** + * [1261] Find Elements in a Contaminated Binary Tree + */ +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::{collections::HashSet, collections::VecDeque, cell::RefCell, rc::Rc}; +struct FindElements { + collected_set: HashSet +} + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl FindElements { + + fn new(root: Option>>) -> Self { + let mut queue = VecDeque::new(); + let mut collected_set = HashSet::new(); + + if let Some(r) = root { + r.borrow_mut().val = 0; + queue.push_back(Rc::clone(&r)); + } + + while !queue.is_empty() { + let top = queue.pop_front().unwrap(); + collected_set.insert(top.borrow().val); + + if let Some(left) = &top.borrow().left { + left.borrow_mut().val = top.borrow().val * 2 + 1; + queue.push_back(Rc::clone(left)); + }; + + if let Some(right) = &top.borrow().right { + right.borrow_mut().val = top.borrow().val * 2 + 2; + queue.push_back(Rc::clone(right)); + }; + } + + FindElements { + collected_set + } + } + + fn find(&self, target: i32) -> bool { + self.collected_set.contains(&target) + } +} + +/** + * Your FindElements object will be instantiated and called as such: + * let obj = FindElements::new(root); + * let ret_1: bool = obj.find(target); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1261() { + } +}