使用队列存储当前层级的节点个数
fun averageOfLevels(root: TreeNode?): DoubleArray {
var queue = LinkedList<TreeNode>()
val sums = arrayListOf<Double>()
if (null == root) return doubleArrayOf()
queue.add(root)
var size = 1
while (queue.isNotEmpty()) {
var tempSum = 0.0
val tempCount = size
var nextLCount = 0
while (size > 0) {
val node = queue.poll()
tempSum += node.`val`
if (null != node.left) {
queue.add(node.left)
nextLCount++
}
if (null != node.right) {
queue.add(node.right)
nextLCount++
}
size--
}
sums.add(tempSum / tempCount)
size = nextLCount
}
val doubleArray = DoubleArray(sums.size)
sums.forEachIndexed { index, d ->
doubleArray.set(index,d)
}
return doubleArray
}