Java BFS solution


  • 0
    M
    public class Solution {
        
        public List<Double> averageOfLevels(TreeNode root) {
            List<Double> result = new ArrayList<>();
            Queue<TreeNode> queue = new ArrayDeque<>();
            queue.add(root);
            while (!queue.isEmpty()) {
            
                int n = queue.size();
                double sum = 0;
                
                for (int i = 0; i < n; i++) {
                    TreeNode node = queue.poll();
                    sum += node.val;
                    
                    if (node.left != null) queue.offer(node.left);
                    if (node.right != null) queue.offer(node.right);
                }
                
                result.add(sum / n);
                
            }
            
            return result;
    
        }
        
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.