go: add «515. Find Largest Value in Each Tree Row»
URL: https://leetcode.com/problems/find-largest-value-in-each-tree-row/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
b78dbab383
commit
9e974ce0d6
1 changed files with 35 additions and 0 deletions
35
go/find-largest-value-in-each-tree-row.go
Normal file
35
go/find-largest-value-in-each-tree-row.go
Normal file
|
@ -0,0 +1,35 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
aq "github.com/emirpasic/gods/v2/queues/arrayqueue"
|
||||
)
|
||||
|
||||
func largestValues(root *TreeNode) []int {
|
||||
q := aq.New[*TreeNode]()
|
||||
if root != nil {
|
||||
q.Enqueue(root)
|
||||
}
|
||||
|
||||
largest := make([]int, 0)
|
||||
for !q.Empty() {
|
||||
node, _ := q.Peek()
|
||||
foundMax := node.Val
|
||||
|
||||
n := q.Size()
|
||||
for i := 0; i < n; i++ {
|
||||
node, _ := q.Dequeue()
|
||||
foundMax = max(foundMax, node.Val)
|
||||
|
||||
if node.Left != nil {
|
||||
q.Enqueue(node.Left)
|
||||
}
|
||||
if node.Right != nil {
|
||||
q.Enqueue(node.Right)
|
||||
}
|
||||
}
|
||||
|
||||
largest = append(largest, foundMax)
|
||||
}
|
||||
|
||||
return largest
|
||||
}
|
Loading…
Reference in a new issue