add new solutions
This commit is contained in:
parent
9c2c959a9b
commit
9a10695e8c
29 changed files with 1074 additions and 2 deletions
45
solutions/13/q1339/solution.go
Normal file
45
solutions/13/q1339/solution.go
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
package q1339
|
||||
|
||||
type TreeNode struct {
|
||||
Val int
|
||||
Left *TreeNode
|
||||
Right *TreeNode
|
||||
}
|
||||
|
||||
func sumSumTrees(node *TreeNode) int {
|
||||
if node == nil {
|
||||
return 0
|
||||
}
|
||||
node.Val += sumSumTrees(node.Left) + sumSumTrees(node.Right)
|
||||
return node.Val
|
||||
}
|
||||
|
||||
func findNearest(node *TreeNode, target int) int {
|
||||
if node == nil {
|
||||
return -1
|
||||
}
|
||||
ret := node.Val
|
||||
l, r := findNearest(node.Left, target), findNearest(node.Right, target)
|
||||
if abs(l-target) < abs(ret-target) {
|
||||
ret = l
|
||||
}
|
||||
if abs(r-target) < abs(ret-target) {
|
||||
ret = r
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func abs(n int) int {
|
||||
if n < 0 {
|
||||
return -n
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func maxProduct(root *TreeNode) int {
|
||||
totalSum := sumSumTrees(root)
|
||||
nearest := findNearest(root, totalSum/2)
|
||||
return nearest * (totalSum - nearest) % (1e9 + 7)
|
||||
}
|
||||
|
||||
var _ = maxProduct
|
||||
Loading…
Add table
Add a link
Reference in a new issue