#637
Easy Algorithms Average of levels in binary tree
Tree Depth-First Search Breadth-First Search Binary Tree
74.7% acceptance
Feb 20, 2026
5556
352
Given the root of a binary tree, return the average value of the nodes
on each level.
Solution
Rust
Time O(n²)
Space O(n)
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn average_of_levels(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
let mut result = Vec::new();
let mut queue = std::collections::VecDeque::new();
if let Some(r) = root {
queue.push_back(r);
}
while !queue.is_empty() {
let level_size = queue.len();
let mut sum = 0i64;
for _ in 0..level_size {
let node = queue.pop_front().unwrap();
let b = node.borrow();
sum += b.val as i64;
if let Some(l) = b.left.clone() { queue.push_back(l); }
if let Some(r) = b.right.clone() { queue.push_back(r); }
}
result.push(sum as f64 / level_size as f64);
}
result
}
}