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
    }
}

 

posted @ 2020-07-02 01:00  johnny_zhao  阅读(98)  评论(0编辑  收藏  举报