Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxPathSum(TreeNode root) {
if(root == null) return 0;
int[] max = new int[1];
max[0] = Integer.MIN_VALUE;
maxSum(root,max);
return max[0];
}
public int maxSum(TreeNode root,int[] max)
{
if(root == null) return 0;
// if(root.left == null && root.right == null) return root.val>0?root.val:0;
int leftvalue = maxSum(root.left,max);
int rightvalue = maxSum(root.right,max);
int value = Math.max(leftvalue + root.val,rightvalue + root.val);
int value2 = Math.max(value,root.val);
int value3 = Math.max(value2,leftvalue + root.val + rightvalue);
max[0] = Math.max(max[0],value3);
return value2;
}
}
注意:参考了网上的解法。1,需要用数组进行数值的传值。2,需要比较left+val,right+val,val,left+val+right,oldmax。 3,不能返回value3,因为意味着不能走root的parent了。4,但仍需要考虑value3的状况,所以用存储的max来返回最终的结果