mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
go: add «1038. Binary Search Tree to Greater Sum Tree»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
6c0af823be
commit
70419f93de
1 changed files with 26 additions and 0 deletions
26
go/binary-search-tree-to-greater-sum-tree.go
Normal file
26
go/binary-search-tree-to-greater-sum-tree.go
Normal file
|
@ -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
|
||||
}
|
Loading…
Reference in a new issue