I am trying to solve LeetCode problem 124. Binary Tree Maximum Path Sum:
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the
rootof a binary tree, return the maximum path sum of any non-empty path.Example 1:
Input:
root = [1,2,3]
Output:6
Explanation: The optimal path is2 -> 1 -> 3with a path sum of2 + 1 + 3 = 6.Constraints:
- The number of nodes in the tree is in the range
[1, 3 * 104].-1000 <= Node.val <= 1000
This is my code:
class Solution {
public int maxPathSum(TreeNode root) {
int[] max= new int[1];
int res = dia(root, max);
return max[0];
}
public static int dia(TreeNode root,int[] max){
if(root==null){
return 0;
}
int lh = Math.max(0,dia(root.left, max));
int rh = Math.max(0,dia(root.right, max));
max[0] = Math.max(max[0], lh+rh+root.val);
return root.val + Math.max(lh,rh);
}
}
For the input [-3] (which is a tree with just one node, having the value -3), my code returns 0, but the expected answer is -3.
How to account for this particular test case?
I am simply taking the max of 0 and the recursive calls to discount negative node values.
Since it doesn't make sense to add a negative value, I decided to take max of 0 and the recursive calls root.left, similarly for 0 and root.right.
But now I don't know how to go about a single node with negative value.
How should I adapt my code to cover such cases?
