【leetcode】637. 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.

解析

给一颗树,求每一层的平均数,返回一个List

思路

我的想法是将一层的所有节点加入到一个list中,计算list的平均数,并递归计算list中节点的子节点(会构建多个list,空间利用较多)
最优解是使用了广度优先算法,利用queue将一层的节点先全部入列,计算平均数,并将其子节点入列,每层循环用n记录当前queue中的节点数,作为内层循环的循环次数

我的解法

public List<Double> averageOfLevels(TreeNode root) {
        List<Double> avg = new ArrayList<>();
        if (root == null) {
            return null;
        }
        List<TreeNode> list = new ArrayList<TreeNode>() {
            {
                add(root);
            }
        };
        getAvg(list, avg);
        return avg;
    }

    private void getAvg(List<TreeNode> list, List<Double> avg) {
        if (list == null || list.size() <= 0) {
            return;
        }
        List<TreeNode> childTreeNodeList = new ArrayList<>();
        Double sum = 0D;
        for (TreeNode t : list) {
            sum += t.val;
            if (t.left != null) {
                childTreeNodeList.add(t.left);
            }
            if (t.right != null) {
                childTreeNodeList.add(t.right);
            }
        }
        avg.add(sum / list.size());
        getAvg(childTreeNodeList, avg);
    }

最优解

public List<Double> averageOfLevelsBFS(TreeNode root) {
        if (root == null) {
            return null;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>() {
            {
                add(root);
            }
        };
        List<Double> avg = new ArrayList<>();
        while (!queue.isEmpty()) {
            //queue的长度为当前行的元素数
            int n = queue.size();
            Double sum = 0D;
            for (int i = 0; i < n; i++) {
                TreeNode t = queue.poll();
                sum += t.val;
                if (t.left != null) {
                    queue.offer(t.left);
                }
                if (t.right != null) {
                    queue.offer(t.right);
                }
            }
            avg.add(sum / n);
        }
        return avg;
    }
posted @ 2017-07-20 16:36  l.shane  阅读(285)  评论(0编辑  收藏  举报