From 33c079738631c552185ba8476c893b90ecf477d0 Mon Sep 17 00:00:00 2001 From: marspere <1587393449@qq.com> Date: Fri, 19 Aug 2022 13:50:48 +0800 Subject: [PATCH] =?UTF-8?q?Update=200102:=E4=BC=98=E5=8C=96=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86?= =?UTF-8?q?=E4=B8=AD637=E9=A2=98=E7=9A=84go=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 46 ++++++++++------------- 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index a1a7baed..25189dba 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1054,40 +1054,34 @@ go: 637. 二叉树的层平均值 */ func averageOfLevels(root *TreeNode) []float64 { - res:=[][]int{} - var finRes []float64 - if root==nil{//防止为空 - return finRes + if root == nil { + // 防止为空 + return nil } - queue:=list.New() + res := make([]float64, 0) + queue := list.New() queue.PushBack(root) - var tmpArr []int - for queue.Len()>0 { - length:=queue.Len()//保存当前层的长度,然后处理当前层(十分重要,防止添加下层元素影响判断层中元素的个数) - for i:=0;i 0 { + //保存当前层的长度,然后处理当前层(十分重要,防止添加下层元素影响判断层中元素的个数) + length := queue.Len() + for i := 0; i < length; i++ { + node := queue.Remove(queue.Front()).(*TreeNode) + if node.Left != nil { queue.PushBack(node.Left) } - if node.Right!=nil{ + if node.Right != nil { queue.PushBack(node.Right) } - tmpArr=append(tmpArr,node.Val)//将值加入本层切片中 + // 当前层元素求和 + sum += node.Val } - res=append(res,tmpArr)//放入结果集 - tmpArr=[]int{}//清空层的数据 + // 计算每层的平均值,将结果添加到响应结果中 + res = append(res, float64(sum)/float64(length)) + sum = 0 // 清空该层的数据 } - //计算每层的平均值 - length:=len(res) - for i:=0;i