From 4f71ddc10fdacabdb14acfd53cbcee7bb0d7e996 Mon Sep 17 00:00:00 2001 From: marspere <1587393449@qq.com> Date: Fri, 19 Aug 2022 11:28:57 +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=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86=E4=B8=AD?= =?UTF-8?q?515=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 | 52 +++++++++++------------ 1 file changed, 24 insertions(+), 28 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 69f2f594..a1a7baed 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1552,44 +1552,40 @@ go: 515. 在每个树行中找最大值 */ func largestValues(root *TreeNode) []int { - res:=[][]int{} - var finRes []int - if root==nil{//防止为空 - return finRes + if root == nil { + //防止为空 + return nil } - queue:=list.New() + 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)//出队列 + // 比较当前层中的最大值和新遍历的元素大小,取两者中大值 + temp = max(temp, node.Val) + 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)//将值加入本层切片中 } - res=append(res,tmpArr)//放入结果集 - tmpArr=[]int{}//清空层的数据 + ans = append(ans, temp) + temp = math.MinInt64 } - //找到每层的最大值 - for i:=0;i max { - max = val - } + +func max(x, y int) int { + if x > y { + return x } - return max + return y } ```