zoukankan      html  css  js  c++  java
  • 637. Average of Levels in Binary Tree

    package LeetCode_637
    
    import LeetCode_297.TreeNode
    import java.util.*
    import kotlin.collections.ArrayList
    
    /**
     * 637. Average of Levels in Binary Tree
     * https://leetcode.com/problems/average-of-levels-in-binary-tree/description/
     * Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
     * */
    
    class Solution {
        /*
        * solution: BFS, Time complexity:O(n), Space complexity:O(n)
        * */
        fun averageOfLevels(root: TreeNode?): DoubleArray {
            val list = ArrayList<Double>()
            if (root == null) {
                return DoubleArray(0)
            }
            val queue = LinkedList<TreeNode>()
            queue.add(root)
            while (queue.isNotEmpty()) {
                val size = queue.size
                var sum = 0.0
                for (i in 0 until size) {
                    val cur = queue.pop()
                    sum += cur.`val`
                    if (cur.left != null) {
                        queue.offer(cur.left)
                    }
                    if (cur.right != null) {
                        queue.offer(cur.right)
                    }
                }
                list.add(sum / size)
            }
            val result = DoubleArray(list.size)
            var index = 0
            for (item in list) {
                result.set(index, item)
                index++
            }
            return result
        }
    }
  • 相关阅读:
    运算符优先级口诀
    [转] 从最大似然到EM算法浅解
    推荐系统实践整体化总结
    Python-函数
    Python-dict/set
    Python-条件、循环、
    Python-list and tuple
    优先级顺序表
    8.1python类型注解
    9.redis-CacheCloud
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13222543.html
Copyright © 2011-2022 走看看