这个问题看起来很像Binary Tree Maximum Path Sum,但节点值可以是正数,负数或零,结果应该是最大路径产品而不是最大值路径总和。 有人可以帮忙吗?
这是"二叉树最大路径总和的经典解决方案": https://discuss.leetcode.com/topic/4407/accepted-short-solution-in-java/2
public class Solution {
int maxValue;
public int maxPathSum(TreeNode root) {
maxValue = Integer.MIN_VALUE;
maxPathDown(root);
return maxValue;
}
private int maxPathDown(TreeNode node) {
if (node == null) return 0;
int left = Math.max(0, maxPathDown(node.left));
int right = Math.max(0, maxPathDown(node.right));
maxValue = Math.max(maxValue, left + right + node.val);
return Math.max(left, right) + node.val;
}
}
这是最大路径产品的天真解决方案。您可以使用"自定义测试用例"。
对其进行测试here/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int maxProduct = Integer.MIN_VALUE;
class Pair{
int min;
int max;
public Pair(int min, int max){
this.min = min;
this.max = max;
}
}
public int maxPathSum(TreeNode root) {
helper(root);
return maxProduct;
}
public Pair helper(TreeNode root){
if(root == null) return new Pair(0, 0);
Pair left = helper(root.left);
Pair right = helper(root.right);
//update global max product
if(root.val == 0){
maxProduct = Math.max(maxProduct, 0);
}else{
maxProduct = Math.max(maxProduct, root.val);
maxProduct = Math.max(maxProduct, root.val * left.min);
maxProduct = Math.max(maxProduct, root.val * left.max);
maxProduct = Math.max(maxProduct, root.val * right.min);
maxProduct = Math.max(maxProduct, root.val * right.max);
maxProduct = Math.max(maxProduct, root.val * left.min * right.min);
maxProduct = Math.max(maxProduct, root.val * left.min * right.max);
maxProduct = Math.max(maxProduct, root.val * left.max * right.min);
maxProduct = Math.max(maxProduct, root.val * left.max * right.max);
}
int min = 0, max = 0; // if root.val == 0 then , min and max should be 0 both
//calculate min and max path product including root
min = Math.min(min, root.val);
min = Math.min(min, root.val * left.min);
min = Math.min(min, root.val * left.max);
min = Math.min(min, root.val * right.min);
min = Math.min(min, root.val * right.max);
max = Math.max(max, root.val);
max = Math.max(max, root.val * left.min);
max = Math.max(max, root.val * left.max);
max = Math.max(max, root.val * right.min);
max = Math.max(max, root.val * right.max);
return new Pair(min, max);
}
}