mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
Update 0102:优化二叉树层序遍历中515题的go方法
This commit is contained in:
@ -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<length;i++{
|
||||
node:=queue.Remove(queue.Front()).(*TreeNode)//出队列
|
||||
if node.Left!=nil{
|
||||
ans := make([]int, 0)
|
||||
temp := math.MinInt64
|
||||
// 层序遍历
|
||||
for queue.Len() > 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<len(res);i++{
|
||||
finRes=append(finRes,max(res[i]...))
|
||||
}
|
||||
return finRes
|
||||
return ans
|
||||
}
|
||||
func max(vals...int) int {
|
||||
max:=int(math.Inf(-1))//负无穷
|
||||
for _, val := range vals {
|
||||
if val > max {
|
||||
max = val
|
||||
}
|
||||
|
||||
func max(x, y int) int {
|
||||
if x > y {
|
||||
return x
|
||||
}
|
||||
return max
|
||||
return y
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user