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:
Matej Focko 2024-12-25 13:23:01 +01:00
parent b78dbab383
commit 9e974ce0d6
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View 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
}