I am new to recursion and binary trees. I am trying to solve this problem on leetcode.
To find maximum sum path is like finding maximum path between any two nodes, that path may or may not pass through the root; except that with max sum path we want to track sum instead of path length.
My algorithm is passing 91/93 test cases and I just can't figure out what I am missing. Can anyone please provide some direction?
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);
}
}
Try
class Solution {
private int sum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxPathSumHelper(root);
if (root.left != null) {
maxPathSumHelper(root.left);
} else 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(Math.max(leftValue, rightValue), root.val);
}
}
I guess we can a bit simplify our statements here.
This'll simply get accepted:
public final class Solution {
int max;
public final int maxPathSum(final TreeNode root) {
max = Integer.MIN_VALUE;
traverse(root);
return max;
}
private final int traverse(final TreeNode node) {
if (node == null)
return 0;
final int l = Math.max(0, traverse(node.left));
final int r = Math.max(0, traverse(node.right));
max = Math.max(max, l + r + node.val);
return Math.max(l, r) + node.val;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.