From 70419f93dee4b250c782b035fa95455df5918894 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 25 Jun 2024 17:35:08 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB1038.=20Binary=20Search=20Tre?= =?UTF-8?q?e=20to=20Greater=20Sum=20Tree=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/binary-search-tree-to-greater-sum-tree.go | 26 ++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 go/binary-search-tree-to-greater-sum-tree.go diff --git a/go/binary-search-tree-to-greater-sum-tree.go b/go/binary-search-tree-to-greater-sum-tree.go new file mode 100644 index 0000000..2ba12a7 --- /dev/null +++ b/go/binary-search-tree-to-greater-sum-tree.go @@ -0,0 +1,26 @@ +package main + +func bstToGst(root *TreeNode) *TreeNode { + var rec func(*TreeNode, int) int + rec = func(node *TreeNode, toAdd int) int { + if node == nil { + return toAdd + } + + // recurse to right + toAdd = rec(node.Right, toAdd) + + // add to the current value + originalValue := node.Val + node.Val += toAdd + + // pass new sum to the left + toAdd = rec(node.Left, toAdd+originalValue) + + // return new sum + return toAdd + } + rec(root, 0) + + return root +}