-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path637.go
More file actions
30 lines (30 loc) · 657 Bytes
/
637.go
File metadata and controls
30 lines (30 loc) · 657 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func dfs(root *TreeNode, level int, sum *[]float64, count *[]int) {
if root == nil {
return
}
if len(*sum) <= level {
*sum = append(*sum, 0)
*count = append(*count, 0)
}
(*sum)[level] += float64(root.Val)
(*count)[level]++
dfs(root.Left, level+1, sum, count)
dfs(root.Right, level+1, sum, count)
}
func averageOfLevels(root *TreeNode) []float64 {
sum := make([]float64, 0)
count := make([]int, 0)
dfs(root, 0, &sum, &count)
for i := 0; i < len(sum); i++ {
sum[i] /= float64(count[i])
}
return sum
}