Average of Levels in Binary Tree - LeetCode
https://leetcode.com/problems/average-of-levels-in-binary-tree/

• Go 言語で取り組んだメモ

## 所感

• binary tree を走査して Average を float64 配列で return する

## 回答

Average of Levels in Binary Tree - LeetCode
https://leetcode.com/problems/average-of-levels-in-binary-tree/solution/

My solution in Go with explanation - LeetCode Discuss
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/1026005/My-solution-in-Go-with-explanation

``````/**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
func averageOfLevels(root *TreeNode) []float64 {
levels := []float64{}
if root == nil {
return levels
}

levelNodes := []*TreeNode{root}

for len(levelNodes) != 0 {
sum := 0
count := 0
nextLevel := []*TreeNode{}
for _, node := range levelNodes {
sum += node.Val
count += 1
if node.Left != nil {
nextLevel = append(nextLevel, node.Left)
}

if node.Right != nil {
nextLevel = append(nextLevel, node.Right)
}
}

levelNodes = nextLevel
levels = append(levels, float64(sum)/float64(count))
}

return levels
}``````

162 Words

2022/08/19 14:05 +0000