1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/go/binary-search-tree-to-greater-sum-tree.go
2024-06-25 17:35:08 +02:00

26 lines
455 B
Go

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
}