124. Binary Tree Maximum Path Sum
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
Return 6
.
/**
* 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) {
return iterate(root)[1];
}
private int[] iterate(TreeNode root){
int[] res= {0, Integer.MIN_VALUE};
if (root== null) return res;
int[] left= iterate(root.left);
int[] right= iterate(root.right);
int Single= Math.max(left[0], right[0])+ root.val;
res[0]= Math.max(Single, 0);
int Max= Math.max(left[1], right[1]);
res[1]= Math.max(Max, left[0]+right[0]+root.val);
return res;
}
}