From ab3380bf4720b026c617b8e4f13751028117d14f Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 16 Jun 2024 10:41:43 +0800 Subject: [PATCH] 20240616 Finished --- src/problem/mod.rs | 3 +- .../p637_average_of_levels_in_binary_tree.rs | 75 +++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 src/problem/p637_average_of_levels_in_binary_tree.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 1930b57..577617a 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -149,4 +149,5 @@ mod p129_sum_root_to_leaf_numbers; mod p124_binary_tree_maximum_path_sum; mod p173_binary_search_tree_iterator; mod p222_count_complete_tree_nodes; -mod p199_binary_tree_right_side_view; \ No newline at end of file +mod p199_binary_tree_right_side_view; +mod p637_average_of_levels_in_binary_tree; \ No newline at end of file diff --git a/src/problem/p637_average_of_levels_in_binary_tree.rs b/src/problem/p637_average_of_levels_in_binary_tree.rs new file mode 100644 index 0000000..caa8506 --- /dev/null +++ b/src/problem/p637_average_of_levels_in_binary_tree.rs @@ -0,0 +1,75 @@ +/** + * [637] Average of Levels in 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::rc::Rc; +use std::cell::RefCell; +use std::collections::VecDeque; +impl Solution { + pub fn average_of_levels(root: Option>>) -> Vec { + let mut result = vec![]; + + let mut queue = VecDeque::new(); + + if let Some(root) = root { + queue.push_back(root); + } + + while !queue.is_empty() { + let length = queue.len(); + + let mut sum = 0f64; + for _ in 0..length { + let node = queue.pop_front().unwrap(); + + sum += node.borrow().val as f64; + + 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.push(sum / length as f64); + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_637() { + } +}