zoukankan      html  css  js  c++  java
  • 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:

    1. The range of node's value is in the range of 32-bit signed integer.

    思路:首先要使用层次遍历,因为每次遍历后要计算对应层的平均值。所以又需要加上对层次的标记。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<Double> averageOfLevels(TreeNode root) {
            //存放平均值的list
            List<Double> list = new ArrayList<>();
            //存放树的队列,用于层次遍历。
            Queue<TreeNode> queue = new ArrayDeque<>();
            // 存放对应树的层次信息,便于计算均值。
            Queue<Integer> queue1 = new ArrayDeque<>();
            // 初始层级h=0
            int h = 0;
            // 对应层级的节点数
            int n = 0;
            // 对应层级的节点数之和,要用double型。
            double sum = 0;
            
            queue.offer(root);
            // 初始层级放入后+1,根节点只有一个。
            queue1.offer(new Integer(h++));
            while(!queue.isEmpty()){
                root = queue.poll();
                int hh = queue1.poll().intValue();
                // 如果处于同一层,需要将层级+1,并完成平均数计算,放入list
                if(h == hh){
                    h++;
                    list.add(new Double(sum/n));
                    sum = 0;
                    n = 0;
                }
                sum += root.val;
                n++;
                // 层次遍历,放入左右子树和对应层级
                if(root.left != null){
                    queue.offer(root.left);
                    queue1.offer(new Integer(h));
                }
                if(root.right != null){
                    queue.offer(root.right);
                    queue1.offer(new Integer(h));
                }
            }
            // 最后一次的均值未计算,要单独处理
            list.add(new Double(sum/n));
            return list;
        }
    }
  • 相关阅读:
    Move site collections to a new database
    SharePoint 2010 Site Workflow
    Customizing the Server Ribbon
    [转]深入浅出之正则表达式
    asp.net中MD5加密写法代码
    asp.net中过滤非法字符防止SQL注入
    jQuery中ajax的使用方法
    gridview中用NewSelectedIndex获取选中的ID值
    GridView中得到选中的某行的ID值
    用javascript伪装链接地址状态代码
  • 原文地址:https://www.cnblogs.com/baichangfu/p/7461433.html
Copyright © 2011-2022 走看看