[LeetCode By Go 13]637. Average of Levels in Binary Tree

题目

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example 1:
Input:

  3
   / \
  9  20
    /  \
   15   7

Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

Note:
The range of node's value is in the range of 32-bit signed integer.

分析

二叉树层序遍历

代码

averageOfLevels.go

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */


func averageOfLevel(nodeSlice []*TreeNode) (nextNodeSlice []*TreeNode, avg float64) {
    var sum float64

    num := len(nodeSlice)
    for _, node := range nodeSlice {
        sum += float64(node.Val)
        if nil != node.Left {
            nextNodeSlice = append(nextNodeSlice, node.Left)
        }
        if nil != node.Right {
            nextNodeSlice = append(nextNodeSlice, node.Right)
        }
    }

    avg = sum / float64(num)

    return nextNodeSlice, avg
}

func averageOfLevels(root *TreeNode) []float64 {
    var ret []float64
    var avg float64
    nextNodeSlice := []*TreeNode{root}

    for ; len(nextNodeSlice) > 0; {
        nextNodeSlice, avg = averageOfLevel(nextNodeSlice)
        ret = append(ret, avg)
    }

    return ret
}

测试

averageOfLevels_test.go

package _637_Average_Levels_Binary_Tree

import "testing"


func InitNode(val int, left *TreeNode, right *TreeNode) (ret *TreeNode){
    ret = new(TreeNode)
    ret.Val = val
    ret.Left = left
    ret.Right = right

    return ret
}

func SliceEqual(s1, s2 []float64) bool {
    len1 := len(s1)
    len2 := len(s2)

    if len1 != len2 {
        return false
    }
    for i := 0; i < len1; i++ {
        if s1[i] != s2[i] {
            return false
        }
    }

    return true
}
func TestAverageOfLevels(t *testing.T) {
    l3_1 := InitNode(15, nil, nil)
    l3_2 := InitNode(7, nil, nil)

    l2_1 := InitNode(9, nil, nil)
    l2_2 := InitNode(20, l3_1, l3_2)

    l1 := InitNode(3, l2_1, l2_2)

    ret := AverageOfLevels(l1)

    want := []float64{3, 14.5, 11}

    ok := SliceEqual(ret, want)

    if ok {
        t.Logf("pass")
    } else {
        t.Errorf("fail, want %+v, get %+v", want, ret)
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,489评论 0 23
  • 我在漏雨的窝棚里 看守着即将成熟的苹果 我深信偷苹果的女贼今夜不会光临 但我仍旧守候此地 手电里吐出微黄陈旧的光束...
    扁竹桃仙人阅读 1,488评论 0 6
  • 不是游戏里的微操,而是微观层面的操作。造一个概念方便记忆提取。 宏观层面,作为普通人是无法改变的。 所以作为普通人...
    Y先生说阅读 2,548评论 0 0
  • 感恩今天自然醒,老师说,我们每天醒来已经是个奇迹了 感恩亲爱的父母给了我生命,可以体验生活 感恩金刚智慧可以让我知...
    Lisa93阅读 812评论 0 0
  • 5月27日 温庭筠是我较喜欢的一位词人,他的词总是在说故事。在《梦江南》里他这样写:过尽千帆皆不是,斜晖脉脉水悠悠...
    三宫主阅读 760评论 0 0