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
.
Pay attention to this one.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int max;
public int maxPathSum(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root == null)
return 0;
max = Integer.MIN_VALUE;
get(root);
return max;
}
public int get(TreeNode root){
if(root == null)
return 0;
int left = get(root.left);
int right = get(root.right);
if(left + right + root.val > max)
max = left + right + root.val;
int temp = Math.max(left, right);
return temp + root.val > 0 ? temp + root.val : 0;
}
}