From 9e974ce0d6b5a8fd017cd60070be12ee1fda0752 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 25 Dec 2024 13:23:01 +0100 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB515.=20Find=20Largest=20Value?= =?UTF-8?q?=20in=20Each=20Tree=20Row=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/find-largest-value-in-each-tree-row/ Signed-off-by: Matej Focko --- go/find-largest-value-in-each-tree-row.go | 35 +++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 go/find-largest-value-in-each-tree-row.go 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 +}