luoheng
10/11/2019 - 11:32 AM

averageOfLevels

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func averageOfLevels(root *TreeNode) []float64 {
    res := make([]float64, 0)
    first, second := make([]*TreeNode, 0), make([]*TreeNode, 0)
    first = append(first, root)
    if root != nil {
        res = append(res, float64(root.Val))
    }
    sum := 0
    for len(first) != 0 {
        cur := first[len(first)-1]
        first = first[:len(first)-1]
        if cur.Left != nil {
            sum += cur.Left.Val
            second = append(second, cur.Left)
        }
        if cur.Right != nil {
            sum += cur.Right.Val
            second = append(second, cur.Right)
        }
        if len(first) == 0 && len(second) != 0 {
            res = append(res, float64(sum)/float64(len(second)))
            first, second = second, first
            sum = 0
        }
    }
    return res
}