题目链接
给定一棵二叉树,要求移除一个边,使得剩余两颗二叉树之和的乘积最大
首先求出以每个点为根节点的和,将这个和赋给该点的Val
其次遍历二叉树,尝试切除每一条边,查看切除后剩余两颗树之和的差值,该差值越小则乘积越大
Runtime: 116 ms (beats 90.1%)
Memory Usage: 17.1 MB
func maxProduct(root *TreeNode) int {
var sumNodes func(node *TreeNode) int
sumNodes = func(node *TreeNode) int {
if node == nil {
return 0
}
if node.Left != nil && node.Right != nil {
node.Val += sumNodes(node.Left) + sumNodes(node.Right)
} else if node.Left != nil {
node.Val += sumNodes(node.Left)
} else if node.Right != nil {
node.Val += sumNodes(node.Right)
}
return node.Val
}
var ans int
var ansLeft int
var ansRight int
var traversal func(root *TreeNode, rootVal int)
traversal = func(root *TreeNode, rootVal int) {
if root == nil {
return
}
if root.Left != nil {
val := root.Left.Val - rootVal + root.Left.Val
if val > 0 {
if val < ans {
ans = val
ansLeft = root.Left.Val
ansRight = rootVal - root.Left.Val
}
traversal(root.Left, rootVal)
} else {
if -val < ans {
ans = -val
ansLeft = root.Left.Val
ansRight = rootVal - root.Left.Val
}
}
}
if root.Right != nil {
val := root.Right.Val - rootVal + root.Right.Val
if val > 0 {
if val < ans {
ans = val
ansLeft = root.Right.Val
ansRight = rootVal - root.Right.Val
}
traversal(root.Right, rootVal)
} else {
if -val < ans {
ans = -val
ansLeft = root.Right.Val
ansRight = rootVal - root.Right.Val
}
}
}
}
sumNodes(root)
ans = math.MaxInt32
traversal(root, root.Val)
const mod = 1000000007
return ((ansLeft % mod) * (ansRight % mod)) % mod
}