27.leetCode637:Average of Levels in Binary Tree

来源:互联网 发布:淘宝快递软件 编辑:程序博客网 时间:2024/05/21 09:06

题目: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/

原创粉丝点击