美文网首页LeetCode
二叉树的层平均值

二叉树的层平均值

作者: 习惯了_就好 | 来源:发表于2019-07-18 10:06 被阅读0次

    给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.

    示例 1:

    输入:
    3
    /
    9 20
    /
    15 7
    输出: [3, 14.5, 11]
    解释:
    第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].

    注意:

    节点值的范围在32位有符号整数范围内。
    

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/average-of-levels-in-binary-tree
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        List<List<Long>>list = new ArrayList<List<Long>>();
        
        public List<Double> averageOfLevels(TreeNode root) {
            List<Double> result = new ArrayList<>();
            
            handleTree(root,0);
            
            int listSize = list.size();
            for(int i = 0; i < listSize; i++){
                List<Long> temp = list.get(i);
                int tempSize = temp.size();
                if(tempSize == 1){
                    result.add(Double.valueOf(temp.get(0)));
                } else {
                    //int越界。。。
                    long sum = 0L;
                    for(int j = 0; j < tempSize; j++){
                        sum += temp.get(j);
                    }
                    
                    result.add(sum * 1.0 / tempSize);
                    
                }
            }
            
            return result;
        }
        
        private void handleTree(TreeNode root,int leval){
            if(root == null) return;
            List<Long> temp;
            if(leval < list.size()){
                temp = list.get(leval);
                temp.add(Long.valueOf(root.val));
            } else {
                temp = new ArrayList();
                temp.add(Long.valueOf(root.val));
                list.add(temp);
            }
             handleTree(root.left, leval + 1);
             handleTree( root.right,leval + 1);
        }
    }
    
    

    相关文章

      网友评论

        本文标题:二叉树的层平均值

        本文链接:https://www.haomeiwen.com/subject/uqsklctx.html