Update 0102:优化二叉树层序遍历中515题的go方法

This commit is contained in:
marspere
2022-08-19 11:28:57 +08:00
parent 10734b6f20
commit 4f71ddc10f

View File

@ -1552,44 +1552,40 @@ go:
515. 在每个树行中找最大值 515. 在每个树行中找最大值
*/ */
func largestValues(root *TreeNode) []int { func largestValues(root *TreeNode) []int {
res:=[][]int{} if root == nil {
var finRes []int //防止为空
if root==nil{//防止为空 return nil
return finRes
} }
queue:=list.New() queue := list.New()
queue.PushBack(root) queue.PushBack(root)
var tmpArr []int ans := make([]int, 0)
//层次遍历 temp := math.MinInt64
for queue.Len()>0 { // 层序遍历
length:=queue.Len()//保存当前层的长度,然后处理当前层(十分重要,防止添加下层元素影响判断层中元素的个数) for queue.Len() > 0 {
for i:=0;i<length;i++{ //保存当前层的长度,然后处理当前层(十分重要,防止添加下层元素影响判断层中元素的个数)
node:=queue.Remove(queue.Front()).(*TreeNode)//出队列 length := queue.Len()
if node.Left!=nil{ 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) queue.PushBack(node.Left)
} }
if node.Right!=nil{ if node.Right != nil {
queue.PushBack(node.Right) queue.PushBack(node.Right)
} }
tmpArr=append(tmpArr,node.Val)//将值加入本层切片中
} }
res=append(res,tmpArr)//放入结果集 ans = append(ans, temp)
tmpArr=[]int{}//清空层的数据 temp = math.MinInt64
} }
//找到每层的最大值 return ans
for i:=0;i<len(res);i++{
finRes=append(finRes,max(res[i]...))
}
return finRes
} }
func max(vals...int) int {
max:=int(math.Inf(-1))//负无穷 func max(x, y int) int {
for _, val := range vals { if x > y {
if val > max { return x
max = val
}
} }
return max return y
} }
``` ```