##### Welcome to Subscribe On Youtube
• import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9  20
/  \
15   7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3,  on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
The range of node's value is in the range of 32-bit signed integer.

*/

public class Average_of_Levels_in_Binary_Tree {

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {

List<Double> result = new ArrayList<>();

// bfs
if (root == null) {
return result;
}

q.offer(root);
int currentLevelCount = 1;
int nextLevelCount = 0;

long currentLevelSum = 0;
int count = 0;

boolean isLevelLeftMost = false;

while (!q.isEmpty()) {
TreeNode current = q.poll();
currentLevelCount--;
count++;

/*

overflow:
Input:
[2147483647,2147483647,2147483647]
Output:
[2147483647.0,-1.0]

short: 32767 or 0x7fff
int: 2147483647 or 0x7fffffff
size_t: 18446744073709551615 or 0xffffffffffffffff
streamsize: 9223372036854775807 or 0x7fffffffffffffff
float: 3.40282e+38 or 0x1.fffffep+127
double: 1.79769e+308 or 0x1.fffffffffffffp+1023

*/

// @note:@memorize: overflow
// change sum from int to long
currentLevelSum += current.val;

if (current.left != null) {
q.offer(current.left);
nextLevelCount++;
}
if (current.right != null) {
q.offer(current.right);
nextLevelCount++;
}

if (currentLevelCount == 0) {
currentLevelCount = nextLevelCount;
nextLevelCount = 0;

// calculate avg

count = 0;
currentLevelSum = 0;
}
}

return result;
}
}
}

############

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode() {}
*     TreeNode(int val) { this.val = val; }
*     TreeNode(int val, TreeNode left, TreeNode right) {
*         this.val = val;
*         this.left = left;
*         this.right = right;
*     }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> ans = new ArrayList<>();
Deque<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while (!q.isEmpty()) {
int n = q.size();
long s = 0;
for (int i = 0; i < n; ++i) {
root = q.pollFirst();
s += root.val;
if (root.left != null) {
q.offer(root.left);
}
if (root.right != null) {
q.offer(root.right);
}
}
}
return ans;
}
}

• // OJ: https://leetcode.com/problems/average-of-levels-in-binary-tree/
// Time: O(N)
// Space: O(N)
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
if (!root) return {};
vector<double> ans;
queue<TreeNode*> q;
q.push(root);
while (q.size()) {
double cnt = q.size(), sum = 0;
for (int i = 0; i < cnt; ++i) {
root = q.front();
q.pop();
sum += root->val;
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
}
ans.push_back(sum / cnt);
}
return ans;
}
};

• # Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
q = deque([root])
ans = []
while q:
s, n = 0, len(q)
for _ in range(n):
root = q.popleft()
s += root.val
if root.left:
q.append(root.left)
if root.right:
q.append(root.right)
ans.append(s / n)
return ans

############

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque

class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
ans = []
queue = deque([root])
while queue:
s = 0
n = len(queue)
for _ in range(n):
top = queue.popleft()
s += top.val
if top.left:
queue.append(top.left)
if top.right:
queue.append(top.right)
ans.append(float(s) / n)
return ans


• /**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
func averageOfLevels(root *TreeNode) []float64 {
q := []*TreeNode{root}
ans := []float64{}
for len(q) > 0 {
n := len(q)
s := 0
for i := 0; i < n; i++ {
root = q[0]
q = q[1:]
s += root.Val
if root.Left != nil {
q = append(q, root.Left)
}
if root.Right != nil {
q = append(q, root.Right)
}
}
ans = append(ans, float64(s)/float64(n))
}
return ans
}

• /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
*     this.val = (val===undefined ? 0 : val)
*     this.left = (left===undefined ? null : left)
*     this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var averageOfLevels = function (root) {
let q = [root];
let ans = [];
while (q.length) {
const n = q.length;
let s = 0;
for (let i = 0; i < n; ++i) {
root = q.shift();
s += root.val;
if (root.left) {
q.push(root.left);
}
if (root.right) {
q.push(root.right);
}
}
ans.push(s / n);
}
return ans;
};


• // 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> {
if root.is_none() {
return Vec::new();
}

let mut q = VecDeque::new();
q.push_back(Rc::clone(&root.unwrap()));
let mut ans = Vec::new();
while !q.is_empty() {
let n = q.len();
let mut sum = 0.0;
for _ in 0..n {
let node = q.pop_front().unwrap();
sum += node.borrow().val as f64;
if node.borrow().left.is_some() {
q.push_back(Rc::clone(node.borrow().left.as_ref().unwrap()));
}
if node.borrow().right.is_some() {
q.push_back(Rc::clone(node.borrow().right.as_ref().unwrap()));
}
}
ans.push(sum / n as f64);
}
ans
}
}


• /**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> averages = new ArrayList<Double>();
if (root == null)
return averages;
queue.offer(root);
while (!queue.isEmpty()) {
double sum = 0;
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
sum += node.val;
TreeNode left = node.left, right = node.right;
if (left != null)
queue.offer(left);
if (right != null)
queue.offer(right);
}
double average = sum / size;
}
return averages;
}
}

############

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode() {}
*     TreeNode(int val) { this.val = val; }
*     TreeNode(int val, TreeNode left, TreeNode right) {
*         this.val = val;
*         this.left = left;
*         this.right = right;
*     }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> ans = new ArrayList<>();
Deque<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while (!q.isEmpty()) {
int n = q.size();
long s = 0;
for (int i = 0; i < n; ++i) {
root = q.pollFirst();
s += root.val;
if (root.left != null) {
q.offer(root.left);
}
if (root.right != null) {
q.offer(root.right);
}
}
}
return ans;
}
}

• // OJ: https://leetcode.com/problems/average-of-levels-in-binary-tree/
// Time: O(N)
// Space: O(N)
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
if (!root) return {};
vector<double> ans;
queue<TreeNode*> q;
q.push(root);
while (q.size()) {
double cnt = q.size(), sum = 0;
for (int i = 0; i < cnt; ++i) {
root = q.front();
q.pop();
sum += root->val;
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
}
ans.push_back(sum / cnt);
}
return ans;
}
};

• # Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
q = deque([root])
ans = []
while q:
s, n = 0, len(q)
for _ in range(n):
root = q.popleft()
s += root.val
if root.left:
q.append(root.left)
if root.right:
q.append(root.right)
ans.append(s / n)
return ans

############

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque

class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
ans = []
queue = deque([root])
while queue:
s = 0
n = len(queue)
for _ in range(n):
top = queue.popleft()
s += top.val
if top.left:
queue.append(top.left)
if top.right:
queue.append(top.right)
ans.append(float(s) / n)
return ans


• /**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
func averageOfLevels(root *TreeNode) []float64 {
q := []*TreeNode{root}
ans := []float64{}
for len(q) > 0 {
n := len(q)
s := 0
for i := 0; i < n; i++ {
root = q[0]
q = q[1:]
s += root.Val
if root.Left != nil {
q = append(q, root.Left)
}
if root.Right != nil {
q = append(q, root.Right)
}
}
ans = append(ans, float64(s)/float64(n))
}
return ans
}

• /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
*     this.val = (val===undefined ? 0 : val)
*     this.left = (left===undefined ? null : left)
*     this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var averageOfLevels = function (root) {
let q = [root];
let ans = [];
while (q.length) {
const n = q.length;
let s = 0;
for (let i = 0; i < n; ++i) {
root = q.shift();
s += root.val;
if (root.left) {
q.push(root.left);
}
if (root.right) {
q.push(root.right);
}
}
ans.push(s / n);
}
return ans;
};


• // 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> {
if root.is_none() {
return Vec::new();
}

let mut q = VecDeque::new();
q.push_back(Rc::clone(&root.unwrap()));
let mut ans = Vec::new();
while !q.is_empty() {
let n = q.len();
let mut sum = 0.0;
for _ in 0..n {
let node = q.pop_front().unwrap();
sum += node.borrow().val as f64;
if node.borrow().left.is_some() {
q.push_back(Rc::clone(node.borrow().left.as_ref().unwrap()));
}
if node.borrow().right.is_some() {
q.push_back(Rc::clone(node.borrow().right.as_ref().unwrap()));
}
}
ans.push(sum / n as f64);
}
ans
}
}