层次遍历+求平均值,Go
中的切片也可以模拟queue
的功能
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func averageOfLevels(root *TreeNode) []float64 {
queue := []*TreeNode{root}
avgList := []float64{}
for len(queue) > 0 {
sum := 0
lenQ := len(queue)
for i := 0; i < lenQ; i++ {
sum += queue[i].Val
if queue[i].Left != nil {
queue = append(queue, queue[i].Left)
}
if queue[i].Right != nil {
queue = append(queue, queue[i].Right)
}
}
// fmt.Println(sum, lenQ)
avgList = append(avgList, float64(sum)/float64(lenQ))
queue = queue[lenQ:]
}
return avgList
}
标签:TreeNode,637,sum,avgList,queue,lenQ,二叉树,leetcode,float64
From: https://www.cnblogs.com/wudanyang/p/17021850.html