average-of-levels-in-binary-tree.dart (1000B)
1 //Given a binary tree find the average of each 2 //level and return the averages as a list. 3 //To do this I used BFS by adding up all of the values 4 //on a given level then dividing by the number of nodes. 5 //I then repeated this for all layers. 6 //Time: 259ms Beats: 100% 7 //Memory: 144.2MB Beats: 50% 8 class Solution { 9 List<double> averageOfLevels(TreeNode? root) { 10 List<TreeNode?> queue = []; 11 queue.add(root); 12 List<double> medians = []; 13 while(queue.length != 0){ 14 int layer_val = 0; 15 int init_length = queue.length; 16 for(int i = 0 ; i < init_length ; ++i){ 17 layer_val += (queue[i]?.val ?? 0); 18 if(queue[i]?.right != null){ 19 queue.add(queue[i]?.right); 20 } 21 if(queue[i]?.left != null){ 22 queue.add(queue[i]?.left); 23 } 24 } 25 medians.add(layer_val / init_length); 26 queue = queue.sublist(init_length); 27 } 28 return medians; 29 } 30 }