mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 21:10:58 +08:00
Update 0102:优化二叉树层序遍历中515题的go方法
This commit is contained in:
@ -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 {
|
for queue.Len() > 0 {
|
||||||
length:=queue.Len()//保存当前层的长度,然后处理当前层(十分重要,防止添加下层元素影响判断层中元素的个数)
|
//保存当前层的长度,然后处理当前层(十分重要,防止添加下层元素影响判断层中元素的个数)
|
||||||
|
length := queue.Len()
|
||||||
for i := 0; i < length; i++ {
|
for i := 0; i < length; i++ {
|
||||||
node := queue.Remove(queue.Front()).(*TreeNode)//出队列
|
node := queue.Remove(queue.Front()).(*TreeNode)//出队列
|
||||||
|
// 比较当前层中的最大值和新遍历的元素大小,取两者中大值
|
||||||
|
temp = max(temp, node.Val)
|
||||||
if node.Left != nil {
|
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(x, y int) int {
|
||||||
|
if x > y {
|
||||||
|
return x
|
||||||
}
|
}
|
||||||
func max(vals...int) int {
|
return y
|
||||||
max:=int(math.Inf(-1))//负无穷
|
|
||||||
for _, val := range vals {
|
|
||||||
if val > max {
|
|
||||||
max = val
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return max
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user