Easy Java Solution traversing levels


  • 0
    S
    public class Solution {
        public List<Double> averageOfLevels(TreeNode root) {
            List<Double> avg = new ArrayList<>();
            if(root == null) {
                return avg;
            }
            
            Deque<TreeNode> q = new ArrayDeque<>();
            q.offerLast(root);
            double size = 0;
            TreeNode curNode = null;
            double prev = 0;
            long total = 0;
            
            while(!q.isEmpty()) {
                size = q.size();
                prev = size;
                total = 0;
                while(size-- > 0) {
                    curNode = q.pollFirst();
                    if(curNode.left != null) {
                        q.offerLast(curNode.left);
                    }
                    
                    if(curNode.right != null) {
                        q.offerLast(curNode.right);
                    }
                    total += curNode.val;
                }
                
                avg.add(total/prev);
            }
            return avg;
        }
    }
    

Log in to reply
 

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