LeetCode 637. Average of Levels in Binary Tree

Problem Statement


// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// 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<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
let mut ans = vec![];
if root.is_none() {
return ans;
}

let mut q = VecDeque::new();
q.push_back(root.clone());
while !q.is_empty() {
let size = q.len();
let mut sum : i64 = 0;
let mut i = size;
while i != 0 {
if let Some(node) = q.pop_front() {
sum += node.clone().unwrap().borrow().val as i64;
let (left, right) = (
node.clone().unwrap().borrow().left.clone(),
node.clone().unwrap().borrow().right.clone()
);
if !left.is_none() {
q.push_back(left);
}
if !right.is_none() {
q.push_back(right);
}
i -= 1;
}
}
ans.push(sum as f64 / size as f64);
}
return ans;
}
}