Java level order traversal solution


  • 0
    S
    
    public class Solution {
        public List<Double> averageOfLevels(TreeNode root) {
            List<Double> res = new ArrayList<Double>();
            if(root == null){
                return res;
            }
            if(root.left == null && root.right == null){
                res.add((double)root.val);
                return res;
            }
            Queue<TreeNode> q = new LinkedList<TreeNode>();
            int curr = 0;
            int next = 1;
            q.add(root);
            while(!q.isEmpty()){
                double sum = 0.0;
                curr = next;
                next = 0;
                for(int i = 0; i<curr; i++){
                    
                    TreeNode ptr = q.poll();
                    sum = sum + ptr.val;
                    if(ptr.left!=null){
                        q.add(ptr.left);
                        next++;
                    }
                    if(ptr.right!=null){
                        q.add(ptr.right);
                        next++;
                    }
                }
                res.add(sum/curr);
            }
            return res;
           
        }
    }
    

Log in to reply
 

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