当前位置 : 主页 > 编程语言 > java >

Average of Levels in Binary Tree

来源:互联网 收集:自由互联 发布时间:2021-06-28
AverageOfLevels.txt public List averageOfLevels(TreeNode root) { List result = new ArrayList(); Queue q = new LinkedList(); if(root == null) return result; q.add(root); while(!q.isEmpty()) { int n = q.size(); double sum = 0.0; for(int i = 0
AverageOfLevels.txt
public List averageOfLevels(TreeNode root) { 
    List result = new ArrayList<>(); 
    Queue q = new LinkedList<>();
    if(root == null) return result;
    q.add(root);
    while(!q.isEmpty()) {
        int n = q.size();
        double sum = 0.0;
        for(int i = 0; i < n; i++) {
            TreeNode node = q.poll();
            sum += node.val;
            if(node.left != null) q.offer(node.left);
            if(node.right != null) q.offer(node.right);
        }
        result.add(sum / n);
    }
    return result;
}
网友评论