27.leetCode637:Average of Levels in Binary Tree

题目:Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

Note:
The range of node’s value is in the range of 32-bit signed integer.

题意:给定一棵二叉树,计算出二叉树的每一层上节点value的平均值。

思路:遍历二叉树,重点在于如何确定层数。可采用Queue,首先把根节点加到queue中,为第一层;移除根节点,然后把根节点的左、右孩子加到queue中,遍queue中的节点即为第二层上的节点…..

代码

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        if(root == null)
            return null;
        List<Double> result = new ArrayList<Double>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            double sum = 0;
            for(int i=0;i<size;i++){
                TreeNode current = queue.poll();
                sum = sum + current.val;
                if(current.left!=null)
                    queue.offer(current.left);
                if(current.right!=null)
                    queue.offer(current.right);
            }
            result.add(sum/size);

        }

        return result;

    }

}


1.建立Queue是用 new LinkedList<>();
2.queue的添加元素有add/offer,删除元素有remove/poll。
(1) offer,add区别:
一些队列有大小限制,因此如果想在一个满的队列中加入一个新项,多出的项就会被拒绝。
这时新的 offer 方法就可以起作用了。它不是对调用 add() 方法抛出一个 unchecked 异常,而只是得到由 offer() 返回的 false。

(2) poll,remove区别:
remove() 和 poll() 方法都是从队列中删除第一个元素。remove() 的行为与 Collection 接口的版本相似,
但是新的 poll() 方法在用空集合调用时不是抛出异常,只是返回 null。因此新的方法更适合容易出现异常条件的情况

还有一种DFS的解法:https://leetcode.com/problems/average-of-levels-in-binary-tree/solution/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值