二叉树的层平均值 (Average of Levels in Binary Tree)

 

思路:

// @Title: 二叉树的层平均值 (Average of Levels in Binary Tree)
// @Author: qisiii
// @Date: 2024-09-14 23:30:47
// @Runtime: 3 ms
// @Memory: 44.3 MB
// @comment: 
// @flag: 
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
List<Double> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            Long sum=0l;
            int size = queue.size();
            for(int i=0;i<size;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((double)sum/size);
        }
        return result;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18