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
        }
    }
  • 相关阅读:
    jmeter录制
    Jmeter之逻辑控制器
    Jmeter关联
    Jmeter之HTTP请求默认值
    shell一文入门通
    Linux系统编程——基础命令总结
    前端专业方向的尽头
    锤子,技术与交互体验细节
    学习汇总 2019-12-2
    不容错过的 Babel7 知识
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13222543.html
Copyright © 2011-2022 走看看