【发布时间】:2020-11-29 11:15:40
【问题描述】:
我是递归和二叉树的新手。我正在尝试解决 leetcode 上的this problem。
求最大和路径就像求任意两个节点之间的最大路径,该路径可能经过也可能不经过根节点;除了最大和路径我们想要跟踪总和而不是路径长度。
我的算法通过了 91/93 个测试用例,但我无法弄清楚我缺少什么。谁能给点方向?
class Solution {
private int sum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxPathSumHelper(root);
if(root.left != null){
maxPathSumHelper(root.left);
}
if(root.right != null){
maxPathSumHelper(root.right);
}
return sum;
}
public int maxPathSumHelper(TreeNode root){
if(root == null){
return 0;
}
//check left sum
int leftValue = root.val + maxPathSumHelper(root.left);
if(leftValue > sum){
sum = leftValue;
}
//check right sum
int rightValue = root.val + maxPathSumHelper(root.right);
if(rightValue > sum){
sum = rightValue;
}
//check if root value is greater
if(root.val > sum){
sum = root.val;
}
//check if right and left value is the greatest
if((leftValue + rightValue - (2 * root.val) )+ root.val > sum){
sum = (leftValue + rightValue - (2 * root.val)) + root.val;
}
return Math.max(leftValue, rightValue);
}
}
【问题讨论】:
-
对我来说,这个任务看起来更像是一个最大和子树,而不是一条路径。
标签: java algorithm recursion binary-tree