diff --git a/go/find-largest-value-in-each-tree-row.go b/go/find-largest-value-in-each-tree-row.go new file mode 100644 index 0000000..1af65be --- /dev/null +++ b/go/find-largest-value-in-each-tree-row.go @@ -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 +}