Java BFS Solution


  • 0
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> ret = new ArrayList<>();
        if (root == null) return ret;
        Queue<TreeNode> level = new LinkedList<>();
        level.offer(root);
        int current = 1;
        int next = 0;
        double sum = 0;
        double count = 0;
        while (level.peek() != null) {
            TreeNode current_node = level.poll();
            sum += current_node.val;
            count ++;
            current --;
            if (current_node.left != null) {
                level.offer(current_node.left);
                next ++;
            }
            if (current_node.right != null) {
                level.offer(current_node.right);
                next ++;
            }
            if (current == 0) {
                double avg = sum / count;
                ret.add(avg);
                current = next;
                next = 0;
                sum = 0;
                count = 0;
            }
        }
        return ret;
        
    }

Log in to reply
 

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