Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int maxValue = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
//there should be a global value to record the global maximum
//there should be a right and left tem value
solver(root);
return maxValue;
}
public int solver(TreeNode root){
if(root == null)
return 0;
int left = solver(root.left);
int right = solver(root.right);
int tem = root.val;
//this is to decide when to add the left and right value
if(left > 0)
tem = tem + left;
if(right > 0)
tem = tem + right;
if(tem > maxValue){
maxValue = tem;
}
//here is to return the left and right and the root value
tem = left>right? left+root.val:right+root.val;
if(tem < root.val)
tem = root.val;
return tem;
}
}